﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Reflection;
using System.IO;

namespace cadbom
{

    public partial class BomForm : Form
    {
        private int i = 0;
        private String token = null;
        private String tenant = null;
        private BindingList<BasProcess> basProcessList = null;
        private List<String[]> insertTableDatas = null;
        private BasProduct product = null;
        private BasProduct gblBasProduct = null;
        private List<MrpProcessBom> gblProcessBoms = null;
        private System.Data.DataTable dtBand = null;
        ProcessForm processSelectForm = null;
        MultiSelectForm multiSelectForm = null;
        bool isOpen = false;
        bool checkCopyProduct = false;

        private string baigeBlockCadHandleId;
        Point3d locationPoint3d ;

        InputProduct inputProduct = null;


        public BomForm()
        {
            InitializeComponent();
            this.dataGridView1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e)
            {
                MessageBox.Show(e.Context.ToString());
            };
            this.dataGridView1.EditingControlShowing +=dataGridView1_EditingControlShowing;
            this.dataGridView1.CellClick += dataGridView1_CellClick;
            this.dataGridView1.MouseDown += dataGridView1_MouseDown;
            this.dataGridView1.MouseMove += dataGridView1_MouseMove;
            this.dataGridView1.DragDrop += dataGridView1_DragDrop;
            this.dataGridView1.DragOver += dataGridView1_DragOver;
            //this.dataGridView1.CellEnter +=dataGridView1_CellEnter;
            //this.dataGridView1.CellDoubleClick +=dataGridView1_CellDoubleClick;
            this.textBox1.Text = GValues.productCode;
            this.button9.Text = GValues.clickButtonText;
            this.Move += Form1_Move;

        }
        public void initBomFromData()
        {
            if (GValues.productCode != "")
            {
                this.button2_Click(null, null);
            }
        }

        public void disabledButton9(Boolean flag)
        {
            this.button9.Enabled = flag;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ToolTip ttpSettings = new ToolTip();
            ttpSettings.InitialDelay = 200;
            ttpSettings.AutoPopDelay = 10 * 1000;
            ttpSettings.ReshowDelay = 200;
            ttpSettings.ShowAlways = true;
            ttpSettings.IsBalloon = true;

            string button4TipOverwrite = "设定插入到CAD的表格字段.";
            string button5TipOverwrite = "表格添加行.";
            string button6TipOverwrite = "表格删除行.";
            string button7TipOverwrite = "选择工艺数据.";
            ttpSettings.SetToolTip(button4, button4TipOverwrite); // ckbOverwrite is a checkbox
            ttpSettings.SetToolTip(button5, button5TipOverwrite); // ckbOverwrite is a checkbox
            ttpSettings.SetToolTip(button6, button6TipOverwrite); // ckbOverwrite is a checkbox
            ttpSettings.SetToolTip(button7, button7TipOverwrite); // ckbOverwrite is a checkbox
            //this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            dataGridView1.RowPostPaint += dataGridView1_RowPostPaint;
            dataGridView1.CellEndEdit +=dataGridView1_CellEndEdit;
            //button2.Click += button2_Click;
            //this.textBox1.TextChanged += textBox1_TextChanged;
            //this.textBox1.Enter += textBox1_TextChanged;
            //this.DoubleClick +=BomForm_DoubleClick;
            getServerData();

        }
        private void BomForm_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Size = new Size(983, 647);
            this.MaximumSize = new Size(983, 647);
        }
        private void Form1_Move(object sender, EventArgs e)
        {
            if (isOpen)
            {
                if (multiSelectForm != null)
                {
                    multiSelectForm.changgeLocation();
                }
                if (processSelectForm != null)
                {
                    processSelectForm.changgeLocation();
                }
            }
        }

        #region 百舸

        public void BaigeUpdateCadProcesstCode()
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            // 启动事务
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开图层表
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                // 遍历所有图层
                foreach (ObjectId layerId in lt)
                {
                    // 打开图层表记录
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                    // 检查图层是否锁定
                    if (ltr.IsLocked)
                    {
                        // 解锁图层
                        ltr.UpgradeOpen();
                        ltr.IsLocked = false;
                        ltr.DowngradeOpen();
                    }
                }
                string handle = baigeBlockCadHandleId;
                if (handle != null)
                {
                    ObjectId objId = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);

                    if (!objId.IsNull)
                    {
                        Entity entity = (Entity)tr.GetObject(objId, OpenMode.ForWrite);
                        if (entity is BlockReference)
                        {
                            BlockReference blockRef = entity as BlockReference;
                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);
                            Dictionary<string, Dictionary<string, string>> productProcessResult = new Dictionary<string, Dictionary<string, string>>();
                            Dictionary<String, String> result = new Dictionary<string, string>();
                            string productcode = "";
                            // 遍历块引用中的所有属性
                            int i = 0;
                            int countRows = insertTableDatas.Count;
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);

                                if (attRef.Tag.IndexOf("制程") != -1 || attRef.Tag.IndexOf("製程") != -1)
                                {
                                    string indexCode = null;
                                    if (attRef.Tag.IndexOf("制程") != -1) {
                                          indexCode = attRef.Tag.Replace("制程","");
                                    }                                       
                                    if (attRef.Tag.IndexOf("製程") != -1)
                                    {
                                        indexCode = attRef.Tag.Replace("製程", "");
                                    }                                   
                                    if (indexCode != null && indexCode != "") {
                                        int index = Int32.Parse(indexCode);
                                        if (index <= countRows)
                                        {
                                            attRef.TextString = insertTableDatas[index - 1][0];
                                        }
                                        else
                                        {
                                            attRef.TextString = "";
                                        }
                                    }
                                    //attRef.TextString = "aaa";
                                }
                                ed.WriteMessage("\n属性 {0} 属性值: {1}", attRef.Tag, attRef.TextString);
                                i++;
                            }
                        }
                    }
                }
                else
                {
                    ed.WriteMessage("\n未找到与指定 Handle ID 对应的对象。");
                }
                docLock.Dispose();
                // 提交事务
                tr.Commit();
            }
        }

        public void BaigeBlockGetMainProductCode(Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            BasProductImport importProduct = new BasProductImport();
            string baigeProductCode = "";
            string materialHeigh = "";
            string materialSpec = "";
            string materialFace = "";
            string dwgPath = Path.GetDirectoryName(doc.Name);
            importProduct.customerCode = "C001";
            importProduct.unitName = "PCS";
            importProduct.productVer = "A";
            importProduct.productTypeName = "半成品";
            importProduct.currencyName = "人民币";

            // 选择块
            PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
            blockOptions.SetRejectMessage("\n选择的对象不是块。");
            blockOptions.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult blockResult = ed.GetEntity(blockOptions);
            if (blockResult.Status != PromptStatus.OK)
                return;

            ObjectId blockId = blockResult.ObjectId;

            // 获取块的定义
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                if (blockRef != null)
                {
                    string blockName = blockRef.Name;
                    importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                    baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                    // 输出块引用的信息
                    ed.WriteMessage("\n找到块引用: {0}", blockName);

                    // 遍历块引用中的所有属性
                    foreach (ObjectId attId in blockRef.AttributeCollection)
                    {
                        AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);
                        if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        {
                            importProduct.code = attRef.TextString;
                            importProduct.custCode = attRef.TextString;
                            importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                        {
                            importProduct.name = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_ProductName) //"产品名称"
                        {
                            importProduct.mainName = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                        {
                            materialSpec = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                        {
                            materialHeigh = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SurfaceChuli ) //"表面处理"
                        {
                            materialFace = attRef.TextString;
                        }
                        ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                    }
                }

                trans.Commit();
            }
            //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
            if (importProduct.code == null || importProduct.code == "")
            {
                ed.WriteMessage("\n块内容没定义图号！");
            }
            else
            {
                //importProduct.description = materialSpec + "/" + materialHeigh + "/" + materialFace;
                importProduct.mainCompDesc = materialSpec;
                importProduct.faceProcess = materialFace;
                importProduct.materialThickness = materialHeigh;
                //MessageBox.Show("1:" + importProduct.code);
                BaigeGetProduct(importProduct.code, new Action<BasProduct>(product =>
                {
                    //MessageBox.Show("ok" );
                    if (product != null)
                    {
                        if (product.name == importProduct.mainName && product.name == importProduct.name)
                        {
                            BaigeUpdateProduct(importProduct, new Action<string>(r =>
                            {
                                ed.WriteMessage("\n产品主料号系统获取成功！");
                                GValues.productCode = product.code;
                                callback.Invoke(product.code);
                            }));
                        }
                        else
                        {
                            ed.WriteMessage("\n获取的产品不是主料号！");
                            callback.Invoke(null);
                        }                       
                    }
                    else
                    {
                        //List<BasProductImport> importProductList = new List<BasProductImport>();
                        //importProductList.Add(importProduct);
                        //BaigeSaveProduct(importProductList, new Action<string>((result) =>
                        //{
                        //    if (result != null && result == "ok")
                        //    {
                        //        GValues.productCode = importProduct.code;
                        //        ed.WriteMessage("\n产品料号系统创建成功！");
                        //        callback.Invoke(importProduct.code);
                        //    }
                        //    else
                        //    {
                        //        ed.WriteMessage("\n产品料号没创建成功！");
                        //    }
                        //}));
                        ed.WriteMessage("\n系统没有获取到主料号！");
                        callback.Invoke(null);
                    }
                }));
            }
        }

        public void BaigeBlockGetUpdateProductCode(Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            try
            {
                BasProductImport importProduct = new BasProductImport();
                string baigeProductCode = "";
                string materialHeigh = "";
                string materialSpec = "";
                string materialFace = "";
                string dwgPath = Path.GetDirectoryName(doc.Name);
                importProduct.customerCode = "C001";
                importProduct.unitName = "PCS";
                importProduct.productVer = "A";
                importProduct.productTypeName = "半成品";
                importProduct.currencyName = "人民币";

                // 选择块
                PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
                blockOptions.SetRejectMessage("\n选择的对象不是块。");
                blockOptions.AddAllowedClass(typeof(BlockReference), true);

                PromptEntityResult blockResult = ed.GetEntity(blockOptions);
                if (blockResult.Status != PromptStatus.OK)
                    return;

                ObjectId blockId = blockResult.ObjectId;

                // 获取块的定义
                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                    if (blockRef != null)
                    {
                        string blockName = blockRef.Name;
                        importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                        baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                        // 输出块引用的信息
                        ed.WriteMessage("\n找到块引用: {0}", blockName);

                        // 遍历块引用中的所有属性
                        foreach (ObjectId attId in blockRef.AttributeCollection)
                        {
                            AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);
                            if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                            {
                                String tempCode = "";
                                tempCode = attRef.TextString;
                                tempCode = tempCode.Trim();
                                importProduct.code = tempCode;
                                importProduct.custCode = tempCode;
                                importProduct.localAttachment = dwgPath + "/" + tempCode + ".dwg";
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                            {
                                importProduct.name = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                            {
                                materialSpec = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                            {
                                materialHeigh = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SurfaceChuli) //"表面处理"
                            {
                                materialFace = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_ProductVer) //"表面处理"
                            {
                                importProduct.productVer = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_CustName) //"表面处理"
                            {
                                importProduct.customerCode = attRef.TextString;
                            }
                            ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                        }
                    }

                    trans.Commit();
                }
                //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
                if (importProduct.code == null || importProduct.code == "")
                {
                    ed.WriteMessage("\n块内容没定义图号！");
                }
                else
                {
                    //importProduct.description = materialSpec + "/" + materialHeigh + "/" + materialFace;
                    importProduct.mainCompDesc = materialSpec;
                    importProduct.faceProcess = materialFace;
                    importProduct.materialThickness = materialHeigh;
                    //MessageBox.Show("1:" + importProduct.code);
                    BaigeGetProduct(importProduct.code, new Action<BasProduct>(product =>
                    {
                        //MessageBox.Show("ok" );
                        if (product != null)
                        {
                            //20250715 tt1只负责创建 tt2负责修改
                            BaigeUpdateProduct(importProduct, new Action<string>(r =>
                            {
                                ed.WriteMessage("\n产品料号系统获取成功！");
                                GValues.productCode = product.code;
                                callback.Invoke(product.code);
                            }));

                        }
                        else
                        {
                            ed.WriteMessage("\n产品数据没找到！");
                        }
                    }));
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                ed.WriteMessage("获取产品报错：" + e.Message);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("获取产品报错：" + ex.Message);
            }

        }

        public void updateCadProductCode(List<BasProduct> productList,string handelId, Action<String> callback)
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            BasProduct basProduct = productList[0];
            // 启动事务
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开图层表
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                // 遍历所有图层
                foreach (ObjectId layerId in lt)
                {
                    // 打开图层表记录
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                    // 检查图层是否锁定
                    if (ltr.IsLocked)
                    {
                        // 解锁图层
                        ltr.UpgradeOpen();
                        ltr.IsLocked = false;
                        ltr.DowngradeOpen();
                    }
                }

                string handle = handelId;
                if (handle != null)
                {
                    ObjectId objId = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);

                    if (!objId.IsNull)
                    {
                        Entity entity = (Entity)tr.GetObject(objId, OpenMode.ForWrite);
                        if (entity is BlockReference)
                        {
                            BlockReference blockRef = entity as BlockReference;
                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);
                            Dictionary<string, Dictionary<string, string>> productProcessResult = new Dictionary<string, Dictionary<string, string>>();
                            Dictionary<String, String> result = new Dictionary<string, string>();
                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);

                                if (attRef.Tag == GValues.BlockField_SemiProductCode) //"零件编号"
                                {
                                    if (basProduct.code != null)
                                    {
                                        attRef.TextString = basProduct.code;
                                    }

                                }
                                ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                            }

                        }
                    }
                    else
                    {
                        ed.WriteMessage("\n未找到与指定 Handle ID 对应的对象。");
                    }
                }

                
                // 提交事务
                tr.Commit();
                docLock.Dispose();
                doc.Editor.UpdateScreen();
                doc.Editor.Regen();
                //db.TransactionManager.TopTransaction.DowngradeOpen(); // 确保可以保存更改
                
            }
            callback.Invoke("ok");
        }

        public void BaigeBlockGetProductCode(Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            String tag = "BaigeBlockGetProductCode";
            try
            {
                BasProductImport importProduct = new BasProductImport();
                //string baigeProductCode = "";
                //string materialHeigh = "";
                //string materialSpec = "";
                //string materialFace = "";
                string dwgPath = Path.GetDirectoryName(doc.Name);
                importProduct.customerCode = "C001";
                importProduct.unitName = "PCS";
                importProduct.productVer = "A";
                importProduct.productTypeName = "半成品";
                importProduct.currencyName = "人民币";
                importProduct.sizeLength = "0.0";//this.textBox11.Text; //长度
                importProduct.sizeWidth = "0.0";// this.textBox12.Text; //宽度

                // 选择块
                PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
                blockOptions.SetRejectMessage("\n选择的对象不是块。");
                blockOptions.AddAllowedClass(typeof(BlockReference), true);

                PromptEntityResult blockResult = ed.GetEntity(blockOptions);
                if (blockResult.Status != PromptStatus.OK)
                    return;

                ObjectId blockId = blockResult.ObjectId;

                // 获取块的定义
                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                    if (blockRef != null)
                    {
                        string blockName = blockRef.Name;
                        importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                        baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                        // 输出块引用的信息
                        ed.WriteMessage("\n找到块引用: {0}", blockName);

                        // 遍历块引用中的所有属性
                        foreach (ObjectId attId in blockRef.AttributeCollection)
                        {
                            AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);


                            //2025-11-8
                            if (attRef.Tag == GValues.BlockField_SemiProductCode) //"零件编码"
                            {
                                String tempCode = "";
                                tempCode = attRef.TextString;
                                tempCode = tempCode.Trim();
                                importProduct.code = tempCode;
                                importProduct.localAttachment = dwgPath + "/" + tempCode + ".dwg";
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                            {
                                importProduct.name = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_CustomerCode) //"客户"
                            {
                                importProduct.customerCode = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductDrawingNo) //"零件图号"
                            {
                                importProduct.drawingNo = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductModel) //"零件规格"
                            {
                                importProduct.model = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductDescription) //"零件描述"
                            {
                                importProduct.description = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductCustCode) //"零件客户料号"
                            {
                                importProduct.custCode = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductVer) //"零件版本"
                            {
                                importProduct.productVer = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductSizeLength) //"零件长度"
                            {
                                importProduct.sizeLength = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductSizeWidth) //"零件宽度"
                            {
                                importProduct.sizeWidth = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductWeight) //"零件重量"
                            {
                                importProduct.weight = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductSurfaceChuli) //"零件喷涂"
                            {
                                importProduct.faceProcess = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductCaiLiao) //"零件材料"
                            {
                                importProduct.mainCompDesc = attRef.TextString;
                            }
                            if (attRef.Tag == GValues.BlockField_SemiProductCaiHou) //"零件材料厚度"
                            {
                                importProduct.materialThickness = attRef.TextString;
                            }

                            //if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                            //{
                            //    String tempCode = "";
                            //    tempCode = attRef.TextString;
                            //    tempCode = tempCode.Trim();
                            //    importProduct.code = tempCode;
                            //    importProduct.custCode = tempCode;
                            //    importProduct.localAttachment = dwgPath + "/" + tempCode + ".dwg";
                            //}
                            //if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                            //{
                            //    importProduct.name = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                            //{
                            //    materialSpec = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                            //{
                            //    materialHeigh = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_SurfaceChuli ) //"表面处理"
                            //{
                            //    materialFace = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_ProductVer) //"版本"
                            //{
                            //    importProduct.productVer = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_CustName) //"客户"
                            //{
                            //    importProduct.customerCode = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_CustCode) //"客户料号 放到图号"
                            //{
                            //    importProduct.drawingNo = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_SizeLength) //"长"
                            //{
                            //    importProduct.sizeLength = attRef.TextString;
                            //}
                            //if (attRef.Tag == GValues.BlockField_SizeWidth) //"宽"
                            //{
                            //    importProduct.sizeWidth = attRef.TextString;
                            //}
                            ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                        }
                    }

                    trans.Commit();
                }
                //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
                if ((importProduct.code == null || importProduct.code == "") && !GValues.AutoCreateSemiProductCode)
                {
                    ed.WriteMessage("\n块内容没定义图号！");
                }
                else
                {
                    //importProduct.description = materialSpec + "/" + materialHeigh + "/" + materialFace;
                    //importProduct.mainCompDesc = materialSpec;
                    //importProduct.faceProcess = materialFace;
                    //importProduct.materialThickness = materialHeigh;
                    //MessageBox.Show("1:" + importProduct.code);
                    string semiProductCode = importProduct.code;
                    if (GValues.AutoCreateSemiProductCode && (importProduct.code == null || importProduct.code == ""))
                    {
                        semiProductCode = "共享发大财";
                    }
                    BaigeGetProduct(semiProductCode, new Action<BasProduct>(product =>
                    {
                        SemiProductForm semiProductForm = new SemiProductForm(new Action<string>(check=>{
                            //MessageBox.Show(check);
                            if (check == "save")
                            {
                                List<BasProductImport> importProductList = new List<BasProductImport>();
                                importProductList.Add(importProduct);
                                BaigeSaveProduct(importProductList, new Action<string>((result) =>
                                {
                                    if (result != null && result == "ok")
                                    {
                                        BasProduct basProduct = GValues.createSemiProductCodeList[0];
                                        GValues.productCode = basProduct.code;
                                       
                                        //ed.WriteMessage("\n产品料号系统创建成功！");
                                        MessageBox.Show("产品料号系统不存在，系统创建成功！");
                                        LogHelper.WriteLog(tag + "产品料号系统创建成功！");
                                        updateCadProductCode(GValues.createSemiProductCodeList, baigeBlockCadHandleId, new Action<string>(r => { }));
                                        callback.Invoke(basProduct.code);
                                    }
                                    else
                                    {
                                        MessageBox.Show("产品没有创建成功！");
                                        //ed.WriteMessage("\n产品料号没创建成功！");
                                        LogHelper.WriteLog(tag + "产品料号没创建成功！");
                                        //MessageBox.Show(JsonConvert.SerializeObject(result));
                                    }
                                }));
                            }
                            if (check == "edit")
                            {
                                BaigeUpdateProduct(importProduct, new Action<string>(r =>
                                {
                                    //ed.WriteMessage("\n产品料号系统获取成功！");
                                    MessageBox.Show("产品料号系统已经存在，获取成功！");
                                    LogHelper.WriteLog(tag + "产品料号系统获取成功！");
                                    GValues.productCode = product.code;
                                    callback.Invoke(product.code);
                                }));   
                            }
                            if (check == "cancel")
                            {
                                GValues.productCode = product.code;
                                callback.Invoke(product.code);
                            }
                            }));
                        List<string> checkResults = new List<string>();
                        if (product == null) {
                            semiProductForm.InitFormFields(importProduct,"save",checkResults);
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, semiProductForm);
                        } else {
                            CheckUpdateFields(importProduct, product, checkResults);
                            if (checkResults.Count > 0)
                            {
                                semiProductForm.InitFormFields(importProduct, "edit",checkResults);
                                Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, semiProductForm);
                            }
                            else
                            {
                                semiProductForm.Close();
                                semiProductForm.Dispose();
                                semiProductForm = null;
                                GValues.productCode = product.code;
                                callback.Invoke(product.code);
                                
                            }                            
                        }
                        
                        //semiProductForm.Show();
                       

                        //MessageBox.Show("ok" );
                        //if (product != null)
                        //{
                        //    BaigeUpdateProduct(importProduct, new Action<string>(r =>
                        //    {
                        //        //ed.WriteMessage("\n产品料号系统获取成功！");
                        //        MessageBox.Show("产品料号系统已经存在，获取成功！");
                        //        LogHelper.WriteLog(tag + "产品料号系统获取成功！");
                        //        GValues.productCode = product.code;
                        //        callback.Invoke(product.code);
                        //    }));                           
                        //}
                        //else
                        //{
                        //    List<BasProductImport> importProductList = new List<BasProductImport>();
                        //    importProductList.Add(importProduct);
                        //    BaigeSaveProduct(importProductList, new Action<string>((result) =>
                        //    {
                        //        if (result != null && result == "ok")
                        //        {
                        //            GValues.productCode = importProduct.code;
                        //            //ed.WriteMessage("\n产品料号系统创建成功！");
                        //            MessageBox.Show("产品料号系统不存在，系统创建成功！");
                        //            LogHelper.WriteLog(tag + "产品料号系统创建成功！");
                        //            callback.Invoke(importProduct.code);
                        //        }
                        //        else
                        //        {
                        //            MessageBox.Show("产品没有创建成功！");
                        //            //ed.WriteMessage("\n产品料号没创建成功！");
                        //            LogHelper.WriteLog(tag + "产品料号没创建成功！");
                        //        }
                        //    }));
                        //}
                        int i = 0;
                    }));
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                //ed.WriteMessage("获取产品报错：" + e.Message);
                LogHelper.WriteLog(tag + "获取产品报错！" + e.Message);
            }
            catch (System.Exception ex)
            {
                //ed.WriteMessage("获取产品报错：" + ex.Message);
                LogHelper.WriteLog(tag + "获取产品报错！" + ex.Message);
            }

        }

        private void CheckUpdateFields(BasProductImport productImport, BasProduct product,List<string> checkResults)
        {
            if (productImport.name != product.name)
            {
                checkResults.Add("零件名称：" + product.name + "/" + productImport.name);
            }
            if (productImport.custCode != product.custCode)
            {
                checkResults.Add("客户料号：" + product.custCode + "/" + productImport.custCode);
            }
            if (productImport.drawingNo != product.drawingNo)
            {
                checkResults.Add("零件图号：" + product.drawingNo + "/" + productImport.drawingNo);
            }
            if (productImport.model != product.model)
            {
                checkResults.Add("零件规格：" + product.model + "/" + productImport.model);
            }
            if (productImport.productVer != product.productVer)
            {
                checkResults.Add("零件版本：" + product.productVer + "/" + productImport.productVer);
            }
            if (productImport.description != product.description)
            {
                checkResults.Add("零件描述：" + product.description + "/" + productImport.description);
            }
            if (productImport.mainCompDesc != product.mainCompDesc)
            {
                checkResults.Add("零件材料：" + product.mainCompDesc + "/" + productImport.mainCompDesc);
            }
            if (productImport.faceProcess != product.faceProcess)
            {
                checkResults.Add("表面处理：" + product.faceProcess + "/" + productImport.faceProcess);
            }
            if (productImport.materialThickness != product.materialThickness)
            {
                checkResults.Add("材料厚度：" + product.materialThickness + "/" + productImport.materialThickness);
            }
            if (productImport.sizeLength != product.sizeLength)
            {
                checkResults.Add("长度：" + product.sizeLength + "/" + productImport.sizeLength);
            }
            if (productImport.sizeWidth != product.sizeWidth)
            {
                checkResults.Add("宽度：" + product.sizeWidth + "/" + productImport.sizeWidth);
            }
            if (productImport.weight != product.weight)
            {
                checkResults.Add("重量：" + product.weight + "/" + productImport.weight);
            }
        }    

        public void BaigeUpdateMaterial(BasProductImport basProduct, Action<string> callback)
        {
            String tag = "updateProduct";
            try
            {
                MessageBox.Show("开始保存物料数据！");
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "/bas/basMaterial/cad-edit-local", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<Object> cc = JsonConvert.DeserializeObject<ResponResult<Object>>(r.AckStr());
                        if (cc.success)
                        {
                            callback.Invoke("ok");
                            LogHelper.WriteLog(tag + "保存产品数据成功！");
                        }
                        else
                        {
                            callback.Invoke(null);
                            LogHelper.WriteLog(tag + "BaigeUpdateMaterial-接口访问错误: " + cc.message);
                        }


                    }
                    else
                    {
                        LogHelper.WriteLog(tag + "保存产品数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                    }
                }));
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public void BaigeUpdateProduct(BasProductImport basProduct, Action<string> callback)
        {
            MessageBox.Show("开始保存产品数据！");
            String tag = "updateProduct";
            try
            {
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "/bas/basProduct/cad-edit-local", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<Object> cc = JsonConvert.DeserializeObject<ResponResult<Object>>(r.AckStr());
                        if (cc.success)
                        {
                            callback.Invoke("ok");
                            LogHelper.WriteLog(tag + "保存产品数据成功！");
                        }
                        else
                        {
                            MessageBox.Show(cc.message);
                            callback.Invoke(null);
                            LogHelper.WriteLog(tag + "BaigeUpdateProduct-接口访问错误: " + cc.message);
                        }


                    }
                    else
                    {
                        LogHelper.WriteLog(tag + "保存产品数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                    }
                }));
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public void BaigeSaveProduct(List<BasProductImport> importProductList, Action<string> callback)
        {
            try
            {
                GValues.createSemiProductCodeList = new List<BasProduct>();
                String tag = "saveProductList";
                string postData = JsonConvert.SerializeObject(importProductList);
                Http.CreateHttpClient(GValues.domainLink + "/bas/basProduct/importByExcel", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        ResponResult<Object> cc1 = JsonConvert.DeserializeObject<ResponResult<Object>>(r.AckStr());
                        //MessageBox.Show(JsonConvert.SerializeObject(cc1));
                        ResponResult<BindingList<BasProduct>> cc = JsonConvert.DeserializeObject<ResponResult<BindingList<BasProduct>>>(r.AckStr());
                        if (cc.success && cc.message.IndexOf("导入成功数据:1") != -1)
                        {
                            BindingList<BasProduct> items = cc.result;
                            List<BasProduct> list = items.ToList();
                            GValues.createSemiProductCodeList = list;
                            callback.Invoke("ok");
                            LogHelper.WriteLog(tag + "保存产品数据成功！");
                        }
                        else
                        {
                            callback.Invoke(null);
                            LogHelper.WriteLog(tag + "BaigeSaveProduct-接口访问错误: " + cc.message);
                        }


                    }
                    else
                    {
                        LogHelper.WriteLog(tag + "保存产品数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                    }
                }));
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public void BaigeGetProduct(String productCode, Action<BasProduct> callback)
        {
            //MessageBox.Show(productCode);
            string code = productCode;
            QueryParamater param = new QueryParamater();
            param.superQueryMatchType = "and";
            List<ParamArr> superArrs = new List<ParamArr>();
            ParamArr paramArr = new ParamArr();
            paramArr.rule = "eq";
            paramArr.type = "string";
            paramArr.val = code;
            paramArr.field = "p.code";
            superArrs.Add(paramArr);
            param.superQueryParams = System.Net.WebUtility.UrlDecode(JsonConvert.SerializeObject(superArrs));
            LogHelper.WriteLog("开始查询产品！" + GValues.tenant + " token :" + GValues.token);
            //MessageBox.Show("tenant :" + GValues.tenant + " token :" + GValues.token + " productcode : " + productCode + " domainLink: " + GValues.domainLink);
            String tag = "getProductData";
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basProduct/list?superQueryParams=" + param.superQueryParams + "&superQueryMatchType=" + param.superQueryMatchType, new Action<Http.HttpResp>((r11) =>
            {
                //MessageBox.Show(" r :" + r11.Code);
                int responCode = 0;
                try
                {
                    responCode = Convert.ToInt32(r11.Code);
                }
                catch (System.Exception ex)
                {

                }

                if (r11.Code == HttpStatusCode.OK || responCode == 200) //访问成功
                {
                    ResponResultA<BasProduct> cc = JsonConvert.DeserializeObject<ResponResultA<BasProduct>>(r11.AckStr());
                    if (cc.success)
                    {
                        //MessageBox.Show(" message : " + cc.message);
                        BindingList<BasProduct> products = cc.result.records;
                        BasProduct product = new BasProduct();
                        //MessageBox.Show(" products :" + products.Count);
                        if (products != null && products.Count() == 1)
                        {
                            product = products[0];
                            //MessageBox.Show("product: " + product.code);
                            if (product.code != null && productCode == product.code.Trim())
                            {
                                //MessageBox.Show("exit....");
                                callback.Invoke(product);
                            }
                            else
                            {
                                LogHelper.WriteLog(tag + "没找到产品数据！");
                            }
                        }
                        else
                        {
                            callback.Invoke(null);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog(tag + "BaigeGetProduct-接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    LogHelper.WriteLog(tag + "网络连接错误: " + r11.Error);
                }
            }));
        }
        #endregion

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    InsertTableSelection();
        //}
        #region 表格操作

        //** 插入按钮
        private void button3_Click(object sender, EventArgs e)
        {
        //最大化: this.WindowState = FormWindowState.Maximized;
        //原始大小: this.WindowState = FormWindowState.Normal;
        //最小化: this.WindowState = FormWindowState.Minimized;
            //this.WindowState = FormWindowState.Minimized;
            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("表格中没数据可以插入到CAD表格！");
            }
            else
            {
                insertTableDatas = new List<string[]>();
                foreach (DataGridViewRow item in this.dataGridView1.Rows)
                {
                    insertTableDatas.Add(new string[] {
                        item.Cells[1].FormattedValue.ToString(),
                        item.Cells[2].FormattedValue.ToString(),
                        item.Cells[3].FormattedValue.ToString() ,
                        item.Cells[5].FormattedValue.ToString(),
                        item.Cells[6].FormattedValue.ToString(),
                        item.Cells[7].FormattedValue.ToString(),
                        item.Cells[8].FormattedValue.ToString()
                    });
                }
                this.InsertTableSelection();
            }
        }

        //** 修改按钮
        private void button8_Click(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Minimized;
            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("表格中没数据可以编辑到CAD表格！");
            }
            else
            {

                insertTableDatas = new List<string[]>();
                foreach (DataGridViewRow item in this.dataGridView1.Rows)
                {
                    insertTableDatas.Add(new string[] {
                        item.Cells[1].FormattedValue.ToString(),
                        item.Cells[2].FormattedValue.ToString(),
                        item.Cells[3].FormattedValue.ToString(),
                        item.Cells[5].FormattedValue.ToString(),
                        item.Cells[6].FormattedValue.ToString(),
                        item.Cells[7].FormattedValue.ToString(),
                        item.Cells[8].FormattedValue.ToString()
                    });
                }
                this.UpdateTableSelection();
            }
        }

        public void UpdateTableSelection()
        {
            try
            {
                int recSize = insertTableDatas.Count();//this.dataGridView1.Rows.Count;
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;
                double dwgScale = db.Dimscale;
                DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
                // 输入要选择的表格句柄
                //PromptStringOptions opts = new PromptStringOptions("\nEnter table handle: ");
                //PromptResult handleResult = ed.GetString(opts);

                if (PromptStatus.OK == PromptStatus.OK)
                {
                    string handle = GValues.cadHandleId;// handleResult.StringResult;
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        //BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        //BlockTableRecord modelSpace = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                        ObjectId objectid = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);
                        ObjectId[] ids = new ObjectId[] { objectid };
                        if (ids.Length > 0)
                        {
                            foreach (ObjectId id in ids)
                            {
                                Entity ent = id.GetObject(OpenMode.ForWrite) as Entity;
                                //Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity; 另外一种获取表格的方法
                                if (ent is Table)
                                {
                                    //表格头有2行
                                    Table table = ent as Table;
                                    Cell cell = table.Cells[1, 0];
                                    double textHeight = (double)cell.TextHeight;
                                    ObjectId textStyleId = (ObjectId)cell.TextStyleId;
                                     Autodesk.AutoCAD.Colors.Color color = cell.ContentColor;
                                    //解锁
                                    for (int row = 0; row < (table.Rows.Count - 2); row++)
                                    {

                                        table.Cells[row + 2, 0].State = CellStates.None;
                                        table.Cells[row + 2, 1].State = CellStates.None;
                                        table.Cells[row + 2, 2].State = CellStates.None;
                                        table.Cells[row + 2, 3].State = CellStates.None;
                                        //table.Cells[row + 2, 4].State = CellStates.None;
                                        //table.Cells[row + 2, 5].State = CellStates.None;
                                        //table.Cells[row + 2, 6].State = CellStates.None;
                                        table.Cells[row + 2, 4].State = CellStates.None;

                                        //table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 5].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 6].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 7].State = CellStates.ContentLocked;
                                    }
                                    //
                                        if (recSize > (table.Rows.Count - 2))
                                        {
                                            int newRow = table.Rows.Count; // 添加到倒数第二行，最后一行为标题行
                                            table.InsertRows(newRow, table.Rows[0].Height, (recSize - (table.Rows.Count - 2))); // 在指定位置插入新行

                                        }
                                    if (recSize < ((table.Rows.Count - 2)))
                                    {
                                        int delRows = (table.Rows.Count - 2) - recSize;
                                        int atRow = table.Rows.Count - delRows; // 添加到倒数第二行，最后一行为标题行
                                        //table.DeleteRows(newRow, ( (table.Rows.Count - 2) - recSize));
                                        table.DeleteRows(atRow, delRows);
                                    }
                                    //table.SetTextHeight(2 * dwgScale, 4);
                                    //table.SetTextHeight(2 * dwgScale, 2);
                                    //table.SetTextHeight(2 * dwgScale, 1);
                                    for (int row = 0; row < (table.Rows.Count - 2); row++)
                                    {
                                        table.Cells[row + 2, 0].TextString = (row + 1).ToString();
                                        table.Cells[row + 2, 1].TextString = insertTableDatas[row][0];
                                        table.Cells[row + 2, 2].TextString = insertTableDatas[row][1];
                                        table.Cells[row + 2, 3].TextString = insertTableDatas[row][2];
                                        //table.Cells[row + 2, 4].TextString = insertTableDatas[row][3];
                                        //table.Cells[row + 2, 5].TextString = insertTableDatas[row][4];
                                        //table.Cells[row + 2, 6].TextString = insertTableDatas[row][5];
                                        table.Cells[row + 2, 4].TextString = insertTableDatas[row][6];

                                        table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 5].State = CellStates.ContentLocked;
                                        //table.Cells[row + 2, 6].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 4].State = CellStates.ContentLocked;

                                        table.Cells[row + 2, 0].TextHeight = textHeight;
                                        table.Cells[row + 2, 1].TextHeight = textHeight;
                                        table.Cells[row + 2, 2].TextHeight = textHeight;
                                        table.Cells[row + 2, 3].TextHeight = textHeight;
                                        table.Cells[row + 2, 4].TextHeight = textHeight;

                                        table.Cells[row + 2, 0].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 1].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 2].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 3].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 4].TextStyleId = textStyleId;

                                        table.Cells[row + 2, 0].ContentColor = color;
                                        table.Cells[row + 2, 1].ContentColor = color;
                                        table.Cells[row + 2, 2].ContentColor = color;
                                        table.Cells[row + 2, 3].ContentColor = color;
                                        table.Cells[row + 2, 4].ContentColor = color;

                                        table.Cells[row + 2, 0].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 1].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 2].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 3].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 4].Alignment = CellAlignment.MiddleCenter;
                                    }
                                    //table.GenerateLayout();
                                    //ed.Regen();
                                }
                            }
                        }
                        tr.Commit();
                        docLock.Dispose();
                        // 刷新并保存
                        doc.Editor.UpdateScreen();
                        doc.Editor.Regen();
                    }
                }
            }
            catch (System.Exception err)
            {

            }
        }
        //public double GetCurrentLineTypeScale()
        //{
        //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    using (Transaction tr = db.TransactionManager.StartTransaction())
        //    {
        //        // 获取当前图形的线型定义
        //        ObjectId lineTypeId = db.LineTypeTableId[LayoutManager.Current.CurrentLayoutId];
        //        if (lineTypeId.IsValid)
        //        {
        //            LineTypeTable ltTable = (LineTypeTable)tr.GetObject(db.LineTypeTableId, OpenMode.ForRead);
        //            LineTypeTableRecord ltRec = (LineTypeTableRecord)tr.GetObject(ltTable[lineTypeId], OpenMode.ForRead);

        //            // 获取比率
        //            double scale = ltRec.Scale;
        //            return scale;
        //        }
        //        return 1.0;
        //    }
        //}
        //public static void SetGlobalScaleFactor(double scaleFactor)
        //{
        //    Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    Editor ed = doc.Editor;

        //    using (Transaction tr = db.TransactionManager.StartTransaction())
        //    {
        //        // 获取当前的图纸设置对象
        //        DimStyleTableRecord ds = (DimStyleTableRecord)tr.GetObject(db.Dimstyle, OpenMode.ForWrite);

        //        // 设置全局比例因子
        //        ds.s.SetGlobalScaleFactor(scaleFactor);

        //        tr.AddNewlyCreatedDBObject(ds, true);
        //        tr.Commit();
        //    }

        //    ed.Regen(); // 重新生成图形以应用更改
        //}
        public void InsertTableSelection()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            ObjectId tableObjectid;
            double dwgScale = db.Dimscale;

            // 获取当前视口的比例因子
            double currentViewportScale = 1.0;
            using (ViewTableRecord view = ed.GetCurrentView())
            {
                currentViewportScale = view.Height / view.Width;
            }
            //MessageBox.Show(dwgScale.ToString() + "  " + currentViewportScale.ToString());
            // 定义原始表格的大小和位置
            double tableWidth = 200.0;  // 表格的宽度
            double tableHeight = 60.0;  // 表格的高度
            // 根据视口比例因子调整表格大小
            tableWidth *= currentViewportScale;
            tableHeight *= currentViewportScale;

            // 提示用户选择第一个角点
            // 获取点
            PromptPointOptions pointOptions = new PromptPointOptions("\n请点击位置插入表格");
            PromptPointResult pointResult = ed.GetPoint(pointOptions);
            if (pointResult.Status != PromptStatus.OK)
            {
                ed.WriteMessage("未选择表格插入点。\n");
                return;
            }
                
            //更新插入方式0409 开始
            //PromptPointResult firstPointResult = ed.GetPoint("选择第一个角点: ");
            //if (firstPointResult.Status != PromptStatus.OK)
            //{
            //    ed.WriteMessage("未选择第一个角点。");
            //    return;
            //}

            //Point3d firstPoint = firstPointResult.Value;

            //// 提示用户选择第二个角点
            //PromptPointOptions options = new PromptPointOptions("选择第二个角点: ");
            //options.UseBasePoint = true;
            //options.BasePoint = firstPoint;

            //PromptPointResult secondPointResult = ed.GetCorner("选择第二个角点: ", firstPoint);
            //if (secondPointResult.Status != PromptStatus.OK)
            //{
            //    ed.WriteMessage("未选择第二个角点。");
            //    return;
            //}
            //Point3d secondPoint = secondPointResult.Value;
            //更新插入方式0409 结束
            // 创建范围
            // 手动计算范围
            //double minX = Math.Min(firstPoint.X, secondPoint.X); //更新插入方式0409
            //double minY = Math.Min(firstPoint.Y, secondPoint.Y); //更新插入方式0409
            //double maxX = Math.Max(firstPoint.X, secondPoint.X); //更新插入方式0409
            //double maxY = Math.Max(firstPoint.Y, secondPoint.Y); //更新插入方式0409

            //Extents3d extents = new Extents3d(new Point3d(minX, minY, 0), new Point3d(maxX, maxY, 0));
            //tableHeight = extents.MaxPoint.X - extents.MinPoint.X;
            //tableWidth = (extents.MaxPoint.Y - extents.MinPoint.Y);
            //Extents3d extents = new Extents3d(firstPoint, secondPoint);
            //MessageBox.Show(extents.MaxPoint.X.ToString() + " " + extents.MinPoint.X.ToString());
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 获取当前的图纸设置对象
                //DimStyleTableRecord ds = (DimStyleTableRecord)tr.GetObject(db.Dimstyle, OpenMode.ForWrite);
                //ed.WriteMessage("dimscal: ", ds.Dimscale.ToString());
                tableWidth *= dwgScale; //ds.Dimscale;
                tableHeight *= dwgScale;// ds.Dimscale;

                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord modelSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                int rows = insertTableDatas.Count();
                // 创建一个表格
                Table table = new Table();
                table.TableStyle = db.Tablestyle;
                //table.Position = new Point3d((firstPoint.X + secondPoint.X) / 2, (firstPoint.Y + secondPoint.Y) / 2, 0);  //更新插入方式0409
                //table.Position = new Point3d(0, 0, 0);
                // 确保使用世界坐标
                Point3d worldPoint = ConvertToWorldCoordinate(pointResult.Value, ed);

                table.Position = worldPoint; //20250907 pointResult.Value; //更新插入方式0409
                Point3d newPoint = new Point3d(pointResult.Value.X + 10, pointResult.Value.Y + 10, pointResult.Value.Z + 10);
                locationPoint3d = newPoint;
                table.SetSize(rows + 2, 5);
                table.SetRowHeight(tableHeight / (rows + 2));
                table.SetColumnWidth(tableWidth / 5);
                table.SetColumnWidth(0,(tableWidth / 5) / 2); //第一列缩小
                table.SetColumnWidth(2, (tableWidth / 5) + (tableWidth / 5) / 2); //第三列增加
                //RowType.DataRow
                table.SetTextHeight(2 * dwgScale, 4);
                table.SetTextHeight(2 * dwgScale, 2);
                table.SetTextHeight(2 * dwgScale, 1);
                
                //// 设置表格文字的高度
                //double textHeight = 1.5; // 设置文字的高度，单位为当前图纸单位

                //// 设置表格中所有文本的高度
                //double textSize = 5.0; // 设置文本的高度，单位为当前图纸单位
                //foreach (Cell cell in table.Cells)
                //{
                //    if (!cell.IsEmpty)
                //    {
                //        cell.TextHeight = textSize;
                //    }
                //}
                // 将表格添加到模型空间
                modelSpace.AppendEntity(table);
                tr.AddNewlyCreatedDBObject(table, true);

                // 将选定的对象范围设置为表格数据范围
                //table.Cells[0, 0].TextString = "Row 1, Column 1";
                //table.Cells[0, 1].TextString = "Row 1, Column 2";
                //table.Cells[0, 2].TextString = "Row 1, Column 3";
                //table.Cells[1, 0].TextString = "Row 2, Column 1";
                //table.Cells[1, 1].TextString = "Row 2, Column 2";
                //table.Cells[1, 2].TextString = "Row 2, Column 3";
                //table.Cells[2, 0].TextString = "Row 3, Column 1";
                //table.Cells[2, 1].TextString = "Row 3, Column 2";
                //table.Cells[2, 2].TextString = "Row 3, Column 3";

                        //public enum CellStates {
                        //  ContentLocked = 1,
                        //  ContentModifiedAfterUpdate = 8,
                        //  ContentReadOnly = 2,
                        //  FormatLocked = 0x10,
                        //  FormatModifiedAfterUpdate = 0x40,
                        //  FormatReadOnly = 0x20,
                        //  Linked = 4,
                        //  None = 0
                        //}
                //表格名称
                table.Cells[0, 0].TextString = "工艺BOM表格 (" + GValues.productCustCode + ")-" + GValues.account;
                table.Cells[0, 0].Alignment = CellAlignment.MiddleCenter;
                //表格头
                table.Cells[1, 0].TextString = "序号";
                table.Cells[1, 1].TextString = "加工工艺";
                table.Cells[1, 2].TextString = "加工要求";
                table.Cells[1, 3].TextString = "属性";
                //table.Cells[1, 4].TextString = "准备工时";
                //table.Cells[1, 5].TextString = "加工工时";
                //table.Cells[1, 6].TextString = "计件价格";
                table.Cells[1, 4].TextString = "备注";
                for (int row = 0; row < rows; row++)
                {
                    //Cell cell = table.Cells[2, 0];
                    //cell.State = CellStates.ContentLocked;
                    
                    table.Cells[row + 2, 0].TextString = (row + 1).ToString();
                    table.Cells[row + 2, 1].TextString = insertTableDatas[row][0];
                    table.Cells[row + 2, 2].TextString = insertTableDatas[row][1];
                    table.Cells[row + 2, 3].TextString = insertTableDatas[row][2];
                    //table.Cells[row + 2, 4].TextString = insertTableDatas[row][3];
                    //table.Cells[row + 2, 5].TextString = insertTableDatas[row][4];
                    //table.Cells[row + 2, 6].TextString = insertTableDatas[row][5];
                    table.Cells[row + 2, 4].TextString = insertTableDatas[row][6];
                    //锁定
                    table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                    //table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                    //table.Cells[row + 2, 5].State = CellStates.ContentLocked;
                    //table.Cells[row + 2, 6].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                    //居中
                    table.Cells[row + 2, 4].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 0].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 1].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 2].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 3].Alignment = CellAlignment.MiddleCenter;

                }
                tableObjectid = table.ObjectId;
                table.GenerateLayout();
                long aa = table.Handle.Value; //句柄ID
                GValues.cadHandleId = aa.ToString();
                ResultBuffer rb = new ResultBuffer();
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "productCode:"+GValues.productCode));
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "tableType:processBom"));
                table.XData = rb;                
                //string bb = table.Handle.ToString();
                // 提交事务
                tr.Commit();
                // 刷新并保存
                //doc.Editor.UpdateScreen();
                //doc.Editor.Regen();
                //doc.Database.SaveAs("D:\\SampleDrawing.dwg", true, DwgVersion.Current, db.SecurityParameters);
            }
            docLock.Dispose();
            ed.WriteMessage("已在指定位置插入表格。" + GValues.cadHandleId + "\n");
        }

        private Point3d ConvertToWorldCoordinate(Point3d point, Editor ed)
        {
            // 正确的方法：使用Matrix3d进行坐标转换
            Matrix3d ucsToWcs = ed.CurrentUserCoordinateSystem;
            return point.TransformBy(ucsToWcs);
        }
        public void ModifyTable()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            ObjectId objectid = db.GetObjectId(false, new Handle(long.Parse(GValues.cadHandleId)), 0);
            // 选择表格对象
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Table table = tr.GetObject(objectid, OpenMode.ForWrite) as Table;

                ResultBuffer rb = new ResultBuffer();
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "DOMAINID-" + GValues.tenant));
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, GValues.productCode));
                table.XData = rb;
                tr.Commit();
                docLock.Dispose();

            }
        }
        #endregion
        private void getServerData()
        {
            //this.button2.Enabled = false;
            this.disableButton(false);
            tenant = GValues.tenant;
            token = GValues.token;
            getProcessView();
            //Http.CreateHttpClient(GlobalVariables.tenant, GlobalVariables.token).GetAsync(GValues.domainLink + "http://localhost:8080/jeecg-boot/saas/data/get?domain=" + "suzi-info.com", new Action<Http.HttpResp>((r) =>
            //{
            //    var bb = Convert.ToInt32(r.Code);
            //    if (bb == 200) //访问成功
            //    {
            //        tenant = r.AckStr();
            //        //获取了DOMAIN
            //        Http.CreateHttpClient("http://localhost:8080/jeecg-boot/sys/login").PostAsync("{\"username\":\"admin\",\"password\":\"123456\",\"captchaFlag\":\"true\"}", new Action<Http.HttpResp>((r1) =>
            //        {
            //            var responCode = Convert.ToInt32(r1.Code);
            //            if (responCode == 200) //访问成功
            //            {
            //                ResponResult<LoginDTO> cc = JsonConvert.DeserializeObject<ResponResult<LoginDTO>>(r1.AckStr());
            //                if (cc.success)
            //                {
            //                    token = cc.result.token;
            //                    getProcessView();
            //                }
            //                else
            //                {
            //                    MessageBox.Show(cc.message);
            //                }
            //            }
            //            else
            //            {
            //                MessageBox.Show(r1.Error);
            //            }
            //        }));
            //    }
            //    else
            //    {
            //        MessageBox.Show(r.Code + " " + bb + " " + r.Error);
            //    }

            //}));
        }
        private void getProcessView()
        {
            if (processSelectForm != null)
            {
                processSelectForm.Close();
                processSelectForm.Dispose();
                processSelectForm = null;
            }
            //获取到了token   column=createTime,outsourceNo&order=desc
            Http.CreateHttpClient(tenant, token).GetAsync(GValues.domainLink + "bas/basProcess/list?pageSize=100000&column=sortNo&order=asc", new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProcess> cc = JsonConvert.DeserializeObject<ResponResultA<BasProcess>>(r2.AckStr());
                    if (cc.success)
                    {
                        basProcessList = cc.result.records;
                        //this.button2.Enabled = true;
                        this.disableButton(true);
                        //initProcessBomView();
                        // ==== 修复：切换到UI线程并添加异常捕获 ====
                        this.Invoke(new Action(() =>
                        {
                            try
                            {
                                initProcessBomView();
                            }
                            catch (System.ComponentModel.Win32Exception ex)
                            {
                                MessageBox.Show("表格初始化失败: 创建窗口句柄错误 - " + ex.Message);
                            }
                            catch (System.Exception ex)
                            {
                                MessageBox.Show("表格初始化失败: " + ex.Message);
                            }

                        }));

                        // ========================================
                    }
                    else
                    {
                        MessageBox.Show(cc.message);
                    }
                }
                else
                {
                    MessageBox.Show(r2.Error);
                }
            }));

        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (multiSelectForm != null)
            {
                multiSelectForm.Close();
                multiSelectForm = null;
            }
            List<ListItem> selectItems = new List<ListItem>();
            string processId = null;
            var indexRow = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Index;
            var indexCol = ((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex;
            if (this.dataGridView1.CurrentCell.OwningColumn.DataPropertyName == "processId")
            {
                processId = ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[1].Value.ToString();
                foreach (BasProcess item in basProcessList)
                {
                    if (item.id == processId)
                    {
                        ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[10].Value = item.attribute;
                        //foreach (BasProcessRequirement o in item.processRequirements)
                        //{
                        //    selectItems.Add(new ListItem(o.name, o.id));
                        //}
                    }
                }

            }
            if (this.dataGridView1.CurrentCell.OwningColumn.DataPropertyName == "processRequirementDescs")
            {
                processId = ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[1].Value.ToString();
                foreach (BasProcess item in basProcessList)
                {
                    if (item.processRequirements != null && item.processRequirements.Count > 0 && item.id == processId)
                    {
                        foreach (BasProcessRequirement o in item.processRequirements)
                        {
                            selectItems.Add(new ListItem(o.name, o.id));
                        }
                    }
                }
                if (selectItems != null && selectItems.Count > 0)
                {
                    //MessageBox.Show(((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[0].Value.ToString());
                    multiSelectForm = new MultiSelectForm(selectItems, new Action<List<ListItem>>((r) =>
                    {
                        if (r != null && r.Count > 0)
                        {
                            //((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[indexCol].Value = "";
                            //((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells["processRequirement"].Value = "";
                            //MessageBox.Show(String.Join(",", r));
                            foreach (ListItem item in r)
                            {
                                //String inputData = ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells["processRequirement"].Value.ToString();
                                String inputDataText = ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[indexCol].Value.ToString();
                                if (inputDataText != null && inputDataText != "")
                                {
                                    //String[] dataArr = inputData.Split(',');
                                    String[] textArr = inputDataText.Split('/');
                                    String foundElement = Array.Find(textArr, v => v == item.Text);
                                    if (foundElement != null && foundElement != "")
                                    {
                                        //dataArr = dataArr.Where(x => x != item.Value).ToArray();
                                        textArr = textArr.Where(x => x != item.Text).ToArray();
                                        ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[indexCol].Value = string.Join("/", textArr);
                                        //((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells["processRequirement"].Value = string.Join(",", dataArr);                                         
                                    }
                                    else
                                    {
                                        ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[indexCol].Value += "/" + item.Text;
                                        //((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells["processRequirement"].Value += "," + item.Value;
                                    }
                                }
                                if (inputDataText == null || inputDataText == "")
                                {
                                    ((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells[indexCol].Value = item.Text;
                                    //((System.Windows.Forms.DataGridView)(sender)).Rows[indexRow].Cells["processRequirement"].Value = item.Value ;
                                }
                            }
                        }
                        //multiSelectForm.Close();

                    }));
                    //设置所有者，这样一来子窗口就可以调用父窗口的公共方法
                    multiSelectForm.Owner = this;
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, multiSelectForm);
                    //multiSelectForm.Show(this);

                    isOpen = true;
                    //multiSelectForm.Show();
                    this.dataGridView1.Refresh();
                }

            }

        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {

            using
            (SolidBrush b =
            new
            SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
            {

                string
                linenum = e.RowIndex.ToString();
                int
                linen = 0;
                linen = Convert.ToInt32(linenum) + 1;
                string
                line = linen.ToString();
                e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 5);
                SolidBrush B =
                new
                SolidBrush(Color.Red);
            }

        }
        private void initProcessBomView()
        {
            // 创建包含键值对的数据源
            var keyValuePairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("1", "自制"),
                new KeyValuePair<string, string>("2", "外协"),
                new KeyValuePair<string, string>("3", "组合"),
            };
            List<ProcessAttribute> attributeList = new List<ProcessAttribute>();
            attributeList.Add(new ProcessAttribute("1", "自制"));
            attributeList.Add(new ProcessAttribute("2", "外协"));
            attributeList.Add(new ProcessAttribute("3", "组合"));

            // 创建并添加列
            DataGridViewComboBoxColumn processIdColumn = new DataGridViewComboBoxColumn();
            processIdColumn.HeaderText = "加工工艺";
            processIdColumn.DataPropertyName = "processId";
            processIdColumn.DataSource = basProcessList;
            processIdColumn.DisplayMember = "name"; // 显示文本
            processIdColumn.ValueMember = "id";     // 值
            //dataGridView1.Columns.Add(processIdColumn);

            // ==== 修复：为列添加操作添加异常捕获 ====
            try
            {
                dataGridView1.Columns.Add(processIdColumn);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                MessageBox.Show("添加加工工艺列失败: " + ex.Message);
                return; // 终止后续列添加
            }
            // ========================================

            // 创建并添加列
            DataGridViewTextBoxColumn processRequirementsColumn = new DataGridViewTextBoxColumn();
            processRequirementsColumn.HeaderText = "加工要求";
            processRequirementsColumn.DataPropertyName = "processRequirementDescs";
            dataGridView1.Columns.Add(processRequirementsColumn);

            //// 创建 ComboBox 列
            //DataGridViewComboBoxColumn sexColumn = new DataGridViewComboBoxColumn();
            //sexColumn.HeaderText = "性别";
            //// sexColumn.Name = "ComboBoxColumn";
            //sexColumn.DataPropertyName = "Sex";
            //sexColumn.DataSource = keyValuePairs;
            //sexColumn.DisplayMember = "Value"; // 显示文本
            //sexColumn.ValueMember = "Key";     // 值
            //dataGridView1.Columns.Add(sexColumn);

            // 创建并添加列
            DataGridViewComboBoxColumn processAttributeColumn = new DataGridViewComboBoxColumn();
            processAttributeColumn.HeaderText = "属性";
            processAttributeColumn.DataPropertyName = "processAttribute";
            processAttributeColumn.DataSource = attributeList;
            processAttributeColumn.DisplayMember = "name"; // 显示文本
            processAttributeColumn.ValueMember = "id";     // 值
            dataGridView1.Columns.Add(processAttributeColumn);

            // 创建并添加列
            DataGridViewTextBoxColumn equipmentsColumn = new DataGridViewTextBoxColumn();
            equipmentsColumn.HeaderText = "设备";
            equipmentsColumn.DataPropertyName = "equipments";
            dataGridView1.Columns.Add(equipmentsColumn);

            // 创建并添加列
            DataGridViewTextBoxColumn leadTimeColumn = new DataGridViewTextBoxColumn();
            leadTimeColumn.HeaderText = "准备工时";
            leadTimeColumn.DataPropertyName = "leadTime";
            dataGridView1.Columns.Add(leadTimeColumn);

            // 创建并添加列
            DataGridViewTextBoxColumn processTimeColumn = new DataGridViewTextBoxColumn();
            processTimeColumn.HeaderText = "加工工时";
            processTimeColumn.DataPropertyName = "processTime";
            dataGridView1.Columns.Add(processTimeColumn);

            // 创建并添加列
            DataGridViewTextBoxColumn piecePriceColumn = new DataGridViewTextBoxColumn();
            piecePriceColumn.HeaderText = "计件价格";
            piecePriceColumn.DataPropertyName = "piecePrice";
            dataGridView1.Columns.Add(piecePriceColumn);

            // 创建并添加列
            DataGridViewTextBoxColumn remarkColumn = new DataGridViewTextBoxColumn();
            remarkColumn.HeaderText = "备注";
            remarkColumn.DataPropertyName = "remark";
            dataGridView1.Columns.Add(remarkColumn);


        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.OwningColumn.DataPropertyName == "col12")
            {
                ((ComboBox)e.Control).SelectedIndexChanged +=
                                    new EventHandler(ComboBox_SelectedIndexChanged);
            }
        }

        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentCell.ColumnIndex == 1) //.OwningColumn.Name == "processId")
            {
                String processId = this.dataGridView1.CurrentCell.Value.ToString();
                foreach (BasProcess item in basProcessList)
                {
                    if (item.id == processId)
                    {
                       this.dataGridView1.CurrentRow.Cells[10].Value = item.attribute;
                        //foreach (BasProcessRequirement o in item.processRequirements)
                        //{
                        //    selectItems.Add(new ListItem(o.name, o.id));
                        //}
                    }
                }
                //string str = ((ComboBox)sender).Text.ToString();
                //MessageBox.Show(str);
                //绑定第二个COMBOX  
                //System.Data.DataTable dt = new System.Data.DataTable();
                //dt.Columns.Add(new DataColumn("id"));
                //dt.Columns.Add(new DataColumn("text"));

                //for (int i = 0; i < 20; i++)
                //{
                //    DataRow dr = dt.NewRow();
                //    dr[0] = str + i;
                //    dr[1] = str + i;
                //    dt.Rows.Add(dr);
            }
            //((DataGridViewComboBoxCell)this.dataGridView1.CurrentRow.Cells[4]).DataSource = null;
            //((DataGridViewComboBoxCell)this.dataGridView1.CurrentRow.Cells[4]).DisplayMember = "text";
            //((DataGridViewComboBoxCell)this.dataGridView1.CurrentRow.Cells[4]).ValueMember = "id";
            //((ComboBox)sender).SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
        }
        private void getProcessBom(string productId)
        {
            //获取到了token
            Http.CreateHttpClient(tenant, token).GetAsync(GValues.domainLink + "mrp/mrpProcessBom/list?productId=" + productId, new Action<Http.HttpResp>((r2) =>
            {

                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResult<BindingList<MrpProcessBom>> cc = JsonConvert.DeserializeObject<ResponResult<BindingList<MrpProcessBom>>>(r2.AckStr());
                    if (cc.success)
                    {
                        BindingList<MrpProcessBom> boms = cc.result;
                        if (boms != null && boms.Count() > 0)
                        {
                            boms.Sort(item => item.processSeq);
                        }
                        
                        //initProcessBomView();
                        dtBand = new System.Data.DataTable();

                        dtBand.Columns.Add("processId");
                        dtBand.Columns.Add("processRequirementDescs");
                        dtBand.Columns.Add("processAttribute_dictText");
                        dtBand.Columns.Add("equipments");
                        dtBand.Columns.Add("leadTime");
                        dtBand.Columns.Add("processTime");
                        dtBand.Columns.Add("piecePrice");
                        dtBand.Columns.Add("remark");
                        dtBand.Columns.Add("processId_dictText");
                        dtBand.Columns.Add("processAttribute");
                        dtBand.Columns.Add("id");
                        dtBand.Columns.Add("productId");
                        dtBand.Columns.Add("processRequirement");
                        foreach (MrpProcessBom mpb in boms)
                        {
                            //if (mpb.processRequirements != null && mpb.processRequirements.Count() > 0)
                            //{
                            //    foreach (ProcessRequirements pr in mpb.processRequirements)
                            //    {
                            //        mpb.processRequirementDescs += string.Format("{0}/", pr.name);
                            //    }
                            //    mpb.processRequirementDescs = mpb.processRequirementDescs.TrimEnd('/');
                            //}
                            DataRow dr = dtBand.NewRow();
                            dr["processid"] = mpb.processId;
                            dr["processRequirementDescs"] = mpb.processRequirementDescs;
                            dr["leadTime"] = mpb.leadTime;
                            dr["equipments"] = mpb.equipments;
                            dr["piecePrice"] = mpb.piecePrice;
                            dr["processAttribute"] = mpb.processAttribute;
                            dr["processAttribute_dictText"] = mpb.processAttribute_dictText;
                            dr["processId_dictText"] = mpb.processId_dictText;
                            dr["id"] = mpb.id;
                            dr["processTime"] = mpb.processTime;
                            dr["remark"] = mpb.remark;
                            dr["productId"] = productId;
                            dr["processRequirement"] = "";//mpb.processRequirement; 取消id数据
                            dtBand.Rows.Add(dr);
                        }
                        this.dataGridView1.DataSource = dtBand;
                        //dataGridView1.Columns["processId_dictText"].HeaderText = "加工工艺";
                        //dataGridView1.Columns["processAttribute_dictText"].HeaderText = "属性";
                        //dataGridView1.Columns["equipments"].HeaderText = "设备";
                        //dataGridView1.Columns["leadTime"].HeaderText = "准备工时";
                        //dataGridView1.Columns["processTime"].HeaderText = "加工工时";
                        //dataGridView1.Columns["piecePrice"].HeaderText = "计件价格";
                        //dataGridView1.Columns["remark"].HeaderText = "备注";
                        this.dataGridView1.Columns["processId_dictText"].Visible = false;
                        this.dataGridView1.Columns["id"].Visible = false;
                        this.dataGridView1.Columns["processAttribute_dictText"].Visible = false;
                        this.dataGridView1.Columns["id"].Visible = false;
                        this.dataGridView1.Columns["productId"].Visible = false;
                        this.dataGridView1.Columns["processRequirement"].Visible = false;
                        //this.dataGridView1.Columns[2].ReadOnly = true;
                        foreach (DataGridViewColumn item in dataGridView1.Columns) item.SortMode = DataGridViewColumnSortMode.NotSortable;
                    }
                    else
                    {
                        MessageBox.Show("getProcessBom-接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    MessageBox.Show("网络连接错误: " + r2.Error);
                }
            }));
        }
        public void BaigeSetInputProduct(String baigecode)
        {
            this.textBox1.Text = baigecode;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            int ii = 0;
            ii++;
            string code = this.textBox1.Text;
            QueryParamater param = new QueryParamater();
            param.superQueryMatchType = "and";
            List<ParamArr> superArrs = new List<ParamArr>();
            ParamArr paramArr = new ParamArr();
            paramArr.rule = "eq";
            paramArr.type = "string";
            if (code == null || code == "")
            {
                paramArr.val = GValues.productCode;
            }
            else
            {
                paramArr.val = code;
            }

            paramArr.field = "p.code";
            superArrs.Add(paramArr);
            param.superQueryParams = System.Net.WebUtility.UrlDecode(JsonConvert.SerializeObject(superArrs));
           
            //获取了DOMAIN"1001-000011-00"
            Http.CreateHttpClient(tenant, token).GetAsync(GValues.domainLink + "bas/basProduct/list?superQueryParams=" + param.superQueryParams + "&superQueryMatchType=" + param.superQueryMatchType, new Action<Http.HttpResp>((r11) =>
            {
                var responCode = Convert.ToInt32(r11.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProduct> cc = JsonConvert.DeserializeObject<ResponResultA<BasProduct>>(r11.AckStr());
                    if (cc.success)
                    {
                        BindingList<BasProduct> products = cc.result.records;
                        product = new BasProduct();
                        if (products != null && products.Count() == 1)
                        {
                            product = products[0];
                            if (product.code != null && this.textBox1.Text.Trim() == product.code.Trim())
                            {
                                this.textBox2.Text = product.custId_dictText;
                                this.textBox7.Text = product.productType_dictText;
                                this.textBox16.Text = product.code;
                                this.textBox3.Text = product.custCode;
                                this.textBox8.Text = product.drawingNo;
                                this.textBox15.Text = product.stage_dictText;
                                this.textBox4.Text = product.name;
                                this.textBox9.Text = product.productVer == null ? "" : product.productVer;
                                this.textBox14.Text = product.unitId_dictText;
                                this.textBox5.Text = product.description == null ? "" : product.description;
                                this.textBox10.Text = product.remark;
                                this.textBox13.Text = product.weight;
                                this.textBox18.Text = product.weightUnit_dictText;
                                this.textBox11.Text = product.sizeLength;
                                this.textBox12.Text = product.sizeWidth;
                                this.textBox19.Text = product.widthUnit_dictText;
                                GValues.isCreateQrcode = product.createQrcodeInCad;
                                GValues.qrCodeData = product.code + "/0/" + product.custCode + "/"+ product.id + "/product";
                                GValues.cadHandleId = product.cadHandleId;
                                GValues.productCode = product.code;
                                GValues.productCustCode = product.custCode;
                                this.textBox6.Text = GValues.cadHandleId;
                                getProcessBom(product.id);

                                if (this.button9.Text == "复制")
                                {
                                    this.label1.Visible = true;
                                    this.textBox17.Visible = true;
                                    this.button2.Visible = false;
                                }
                            }
                            else
                            {
                                //MessageBox.Show("没找到产品数据！");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("product："+ GValues.productCode +  "-button2_Click-接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    MessageBox.Show("网络连接错误: " + r11.Error);
                }
            }));
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            this.button2_Click(null, null);
        }

        private void disableButton(Boolean flag)
        {
            this.button5.Enabled = flag;
            this.button6.Enabled = flag;
            this.button7.Enabled = flag;
            this.button3.Enabled = flag;
            this.button1.Enabled = flag;
            this.textBox1.Enabled = flag;
        }
        private void getBomFormData()
        {           
            product.weight = this.textBox13.Text.ToString();
            product.sizeLength = this.textBox11.Text.ToString();
            product.sizeWidth = this.textBox12.Text.ToString();
            product.weightUnit = "40288101710a4c6201710a65913d0002";
            product.widthUnit = "1549037986814283777";
            product.cadHandleId = GValues.cadHandleId;
            gblBasProduct = product;
            gblProcessBoms = ConvertDataTableToList<MrpProcessBom>(dtBand);

        }
        private void getProduct(String code, Dictionary<String, String> result)
        {
            int ii = 0;
            ii++;
            tenant = GValues.tenant;
            token = GValues.token;
            //获取了DOMAIN"1001-000011-00"
            Http.CreateHttpClient(tenant, token).GetAsync(GValues.domainLink + "bas/basProduct/list?queryName=" + code, new Action<Http.HttpResp>((r11) =>
            {
                var responCode = Convert.ToInt32(r11.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProduct> cc = JsonConvert.DeserializeObject<ResponResultA<BasProduct>>(r11.AckStr());
                    if (cc.success)
                    {
                        BindingList<BasProduct> products = cc.result.records;
                        product = new BasProduct();
                        if (products != null && products.Count() == 1)
                        {
                            product = products[0];
                            getProcess(product, result);
                        }
                    }
                    else
                    {
                        MessageBox.Show("getProduct-接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    MessageBox.Show("网络连接错误: " + r11.Error);
                }
            }));
        }
        private void getProcess(BasProduct product, Dictionary<String, String> result)
        {
            tenant = GValues.tenant;
            token = GValues.token;
            //获取到了token   column=createTime,outsourceNo&order=desc
            Http.CreateHttpClient(tenant, token).GetAsync(GValues.domainLink + "bas/basProcess/list?pageSize=100000&column=sortNo&order=asc", new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProcess> cc = JsonConvert.DeserializeObject<ResponResultA<BasProcess>>(r2.AckStr());
                    if (cc.success)
                    {
                        basProcessList = cc.result.records;
                        List<MrpProcessBom> processBoms = new List<MrpProcessBom>();
                         // 另一种简化的写法，使用 var 关键字
                        int i = 0;
                        foreach (var item in result)
                        {
                            if (item.Key.ToString().IndexOf("製程") != -1) {
                                String processName = item.Value;

                                                                // 从 basProcessList 中查找符合 processName 的第一个对象
                                BasProcess basProcess = basProcessList
                                    .FirstOrDefault(p => processName == p.name);

                                if (basProcess != null)
                                {
                                    i++;
                                    MrpProcessBom processBom = new MrpProcessBom();
                                    processBom.processAttribute = basProcess.attribute;
                                    processBom.processId = basProcess.id;
                                    processBom.processSeq = i;
                                    processBom.productId = product.id;
                                    processBom.processRequirement = "";
                                    processBoms.Add(processBom);                                   
                                }
                            }
                        }
                        if (processBoms.Count > 0)
                        {
                            saveProcessBom(product, processBoms, new Action<String>((r) =>
                            {
                                string res = r;
                            }));
                        }
                    }
                    else
                    {
                        MessageBox.Show(cc.message);
                    }
                }
                else
                {
                    MessageBox.Show(r2.Error);
                }
            }));

        }
        public void TT7SaveBomFormData(String code,Dictionary<String,String> result)
        {
            getProduct(code,result);
        }
        private String saveBomFormData(BasProduct basProduct, List<MrpProcessBom> processBoms,string title)
        {
            String res = "false";
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            //Database db = doc.Database;
            Editor ed = doc.Editor;
            try
            {
                int saveCount = 0;
                basProduct.attachment = ""; //后台根据附件判断上更改数据，还是上传图纸
                string postData = JsonConvert.SerializeObject(basProduct);
                Http.CreateHttpClient(GValues.domainLink + "bas/basProduct/cad-edit", tenant, token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        //MessageBox.Show("保存产品修改数据成功！");
                        saveCount++;
                        this.saveProcessBom(basProduct, processBoms,new Action<String>((result)=>{
                            res = result;
                            }));
                    }
                    else
                    {
                        MessageBox.Show("保存产品工艺BOM数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                    }
                }));
                //List<MrpProcessBom> list = ConvertDataTableToList<MrpProcessBom>(dtBand);

            }
            catch (System.Exception err)
            {
                MessageBox.Show("保存产品工艺BOM数据失败！" + err.Message);
            }
            return res;
        }

        private void saveProcessBom(BasProduct basProduct,List<MrpProcessBom> processBoms,Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            //Database db = doc.Database;
            Editor ed = doc.Editor;
            foreach (MrpProcessBom item in processBoms)
            {
                item.id = null;
                item.productId = basProduct.id;
                //item.remark = item.processRequirements_dictText;
            }
            string postData = JsonConvert.SerializeObject(processBoms);
            Http.CreateHttpClient(GValues.domainLink + "mrp/mrpProcessBom/cad-update", tenant, token).PostAsync(postData, new Action<Http.HttpResp>((r1) =>
            {
                var responCode = Convert.ToInt32(r1.Code);
                if (responCode == 200) //访问成功
                {
                    //MessageBox.Show("保存产品工艺BOM数据成功！");
                    //MessageBoxTimeOut.Show("保存成功", title, 1000);
                    //MessageBox.Show("保存产品工艺BOM数据成功！", "提示", MessageBoxButtons.OK);
                    ed.WriteMessage("保存产品工艺BOM数据成功!" + "\n");
                    callback.Invoke("ok");
                }
                else
                {
                    MessageBox.Show("保存产品工艺BOM数据失败！" + r1.Code + " " + " " + responCode + " " + r1.Error);
                }
            }));
        }

        //** 保存按钮

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                product.weight = this.textBox13.Text.ToString();
                product.sizeLength = this.textBox11.Text.ToString();
                product.sizeWidth = this.textBox12.Text.ToString();
                product.weightUnit = "40288101710a4c6201710a65913d0002";
                product.widthUnit = "1549037986814283777";
                product.cadHandleId = GValues.cadHandleId;
                int saveCount = 0;
                string postData = JsonConvert.SerializeObject(product);
                Http.CreateHttpClient(GValues.domainLink + "bas/basProduct/cad-edit", tenant, token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        //MessageBox.Show("保存产品修改数据成功！");
                        saveCount++;
                    }
                    else
                    {
                        MessageBox.Show(r.Code + " " + " " + responCode + " " + r.Error);
                    }
                }));
                List<MrpProcessBom> list = ConvertDataTableToList<MrpProcessBom>(dtBand);
                foreach (MrpProcessBom item in list)
                {
                    item.productId = product.id;
                    //item.remark = item.processRequirements_dictText;
                }
                postData = JsonConvert.SerializeObject(list);
                Http.CreateHttpClient(GValues.domainLink + "mrp/mrpProcessBom/cad-update", tenant, token).PostAsync(postData, new Action<Http.HttpResp>((r1) =>
                {
                    var responCode = Convert.ToInt32(r1.Code);
                    if (responCode == 200) //访问成功
                    {
                        MessageBox.Show("保存产品工艺BOM数据成功！");
                        //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, this);
                        this.Close();
                        this.Dispose();
                        

                        //this.WindowState = FormWindowState.Normal;
                        //this.Size.Width = 391;
                        //this.Size.Height = 240;
                        //this.FormBorderStyle = FormBorderStyle.FixedSingle;
                        //this.Size = new Size(391, 240);
                        //this.MaximumSize = new Size(391, 240);
                    }
                    else
                    {
                        MessageBox.Show(r1.Code + " " + " " + responCode + " " + r1.Error);
                    }
                }));
            }
            catch (System.Exception err)
            {

            }
        }
        public List<T> ConvertDataTableToList<T>(System.Data.DataTable dataTable) where T : new()
        {
            List<T> list = new List<T>();

            foreach (DataRow row in dataTable.Rows)
            {
                T obj = new T();

                foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
                {
                    if (dataTable.Columns.Contains(propertyInfo.Name))
                    {
                        if (row[propertyInfo.Name] != DBNull.Value)
                        {
                            propertyInfo.SetValue(obj, row[propertyInfo.Name], null);
                        }
                    }
                }

                list.Add(obj);
            }

            return list;
        }

        #region 行拖动示例
        //本身窗行的口的拖动，  先做这个
        private Rectangle dragBoxFromMouseDown;
        private int rowIndexFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;
        private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                //如果鼠标移动到矩形框外面，开始拖拽
                if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {
                    if (this.dataGridView1.CurrentCell.ColumnIndex != 2) //按第二列不做操作
                    {
                        //执行tt拖拽，传入数据
                        DragDropEffects dropEffect = dataGridView1.DoDragDrop(dataGridView1.Rows[rowIndexFromMouseDown], DragDropEffects.Move);
                    }
                }
            }
        }


        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            //获取鼠标按下时行的索引值
            rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;

            if (rowIndexFromMouseDown != -1)
            {
                //记录按下鼠标的点
                //DragSize指示在开始拖动操作前鼠标可以移动的范围
                Size dragSize = SystemInformation.DragSize;

                //用DragSize创建一个以鼠标为中心的矩形
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
            else
            {
                //如果鼠标不在datagridview上，重置矩形
                dragBoxFromMouseDown = Rectangle.Empty;
            }
        }


        private void dataGridView1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            //由于鼠标的位置是与屏幕相关的，它必须转换为与客户端相匹配的点
            Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

            //获取鼠标按下时的行的索引值
            rowIndexOfItemUnderMouseToDrop = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
            if (rowIndexOfItemUnderMouseToDrop > 0)
            {
                //如果拖放的行为为从将某一行移动然后移除，插入到某一行
                if (e.Effect == DragDropEffects.Move)
                {
                    DataGridViewRow rowToMove = e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;
                    DataRow dr = ((rowToMove).DataBoundItem as DataRowView).Row;
                    DataRow drr = dtBand.NewRow();
                    drr.ItemArray = dr.ItemArray;
                    dtBand.Rows.RemoveAt(rowIndexFromMouseDown);
                    dtBand.Rows.InsertAt(drr, rowIndexOfItemUnderMouseToDrop);
                }
            }


        }
        #endregion

        private void button7_Click(object sender, EventArgs e)
        {
            if (GValues.processFormClosed)
            {
                processSelectForm = new ProcessForm(basProcessList, new Action<BasProcess>((r) =>
                {
                    try
                    {
                        DataRow dr = dtBand.NewRow();
                        dr["processAttribute"] = r.attribute;
                        if (r.attribute == "1")                                                    
                            dr["processAttribute_dictText"] = "自制";
                        else if (r.attribute == "3")
                        {
                            dr["processAttribute_dictText"] = "组合";
                        }
                        else 
                            dr["processAttribute_dictText"] = "外协";
                        dr["processId"] = r.id;
                        dtBand.Rows.Add(dr);
                        this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
                    }
                    catch (System.Exception err)
                    {

                    }
                }));
                processSelectForm.Owner = this;
                //processSelectForm.Show(this);
                Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, processSelectForm);
                isOpen = true;
                GValues.processFormClosed = false;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                List<int> selectRows = new List<int>();
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                    {
                        string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                        if (checkRows != null && ((string)checkRows) == "1")
                        {
                            selectRows.Add(i);
                        }
                    }

                }
                List<DataRow> rowsToDelete = new List<DataRow>();
                foreach (DataRow row in dtBand.Rows)
                {
                    int rowindex = row.Table.Rows.IndexOf(row);
                    if (selectRows.Contains(rowindex))
                    {
                        rowsToDelete.Add(row);
                    }
                }

                foreach (DataRow row in rowsToDelete)
                {
                    dtBand.Rows.Remove(row);
                }
            }
            catch (System.Exception err)
            {

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                DataRow dr = dtBand.NewRow();
                dr["processAttribute"] = "1";
                dtBand.Rows.Add(dr);
                this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
            } catch (System.Exception err) {

            }
        }

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {

        }

        private void button9_Click(object sender, EventArgs e)
        {
            String res = "";
            GValues.cancelCol = true;
            if (this.button9.Text == "插入")
            {
                if (this.dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("表格中没数据可以插入到CAD表格！");
                }
                else
                {
                    insertTableDatas = new List<string[]>();
                    foreach (DataGridViewRow item in this.dataGridView1.Rows)
                    {
                        insertTableDatas.Add(new string[] {
                        item.Cells[1].FormattedValue.ToString(),
                        item.Cells[2].FormattedValue.ToString(),
                        //item.Cells[3].FormattedValue.ToString() ,
                        item.Cells[10].FormattedValue.ToString(),
                        item.Cells[5].FormattedValue.ToString(),
                        item.Cells[6].FormattedValue.ToString(),
                        item.Cells[7].FormattedValue.ToString(),
                        item.Cells[8].FormattedValue.ToString()
                    });
                    }
                    this.getBomFormData();
                    this.Close(); //操作cad之前关闭窗口
                    if (GValues.CADCreateProductCode && GValues.CadBlockTableProcess) //百舸项目2025427
                    {
                        this.BaigeUpdateCadProcesstCode();
                    }
                    else
                    {
                        this.InsertTableSelection();
                    }

                    if (GValues.isCreateQrcode)
                    {
                        SetObject setObject = new SetObject();
                        setObject.GenerateAndInsertQRCode(GValues.qrCodeData, locationPoint3d, 1.0);
                    }
                    gblBasProduct.cadHandleId = GValues.cadHandleId;
                    res =  this.saveBomFormData(gblBasProduct, gblProcessBoms,"插入");
                }
                ////插入按钮
                //this.button3_Click(null, null);
                ////云保存按钮
                //this.button1_Click(null, null);
            }
            if (this.button9.Text == "修改")
            {
                if (this.dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("表格中没数据可以编辑到CAD表格！");
                }
                else
                {

                    insertTableDatas = new List<string[]>();
                    foreach (DataGridViewRow item in this.dataGridView1.Rows)
                    {
                            insertTableDatas.Add(new string[] {
                            item.Cells[1].FormattedValue.ToString(),
                            item.Cells[2].FormattedValue.ToString(),
                            //item.Cells[3].FormattedValue.ToString(),
                            item.Cells[10].FormattedValue.ToString(),
                            item.Cells[5].FormattedValue.ToString(),
                            item.Cells[6].FormattedValue.ToString(),
                            item.Cells[7].FormattedValue.ToString(),
                            item.Cells[8].FormattedValue.ToString()
                        });
                    }
                    this.getBomFormData();
                    this.Close(); //操作cad之前关闭窗口
                    this.UpdateTableSelection();
                    res = this.saveBomFormData(gblBasProduct, gblProcessBoms,"修改");
                }
                ////修改按钮
                //this.button8_Click(null, null);
                ////云保存按钮
                //this.button1_Click(null, null);

            }
            if (this.button9.Text == "复制")
            {
                if (this.textBox17.Text != "")
                {
                    this.checkProduct();
                }
                else
                {
                    MessageBox.Show("必须输入升版产品编码！");
                }
            }
        }
        private void checkProduct()
        {
            String productCode = this.textBox17.Text;
            //获取了DOMAIN"1001-000011-00"
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basProduct/list?queryName=" + this.textBox17.Text, new Action<Http.HttpResp>((r11) =>
            {
                var responCode = Convert.ToInt32(r11.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<BasProduct> cc = JsonConvert.DeserializeObject<ResponResultA<BasProduct>>(r11.AckStr());
                    if (cc.success)
                    {
                        BindingList<BasProduct> products = cc.result.records;
                        product = new BasProduct();
                        if (products != null && products.Count() == 1)
                        {
                            product = products[0];
                            if (product.code != null && productCode.Trim() == product.code.Trim())
                            {
                                this.saveCopyProduct(product);
                            }
                            else
                            {
                                MessageBox.Show("没找到复制产品数据！");
                            }
                        }
                        else
                        {
                            MessageBox.Show("没找到复制产品数据！");
                        }
                    }
                    else
                    {
                        MessageBox.Show("checkProduct-接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    MessageBox.Show("网络连接错误: " + r11.Error);
                }
            }));
        }
        private void saveCopyProduct(BasProduct basProduct)
        {
            String res = "";
            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("表格中没数据可以插入到CAD表格！");
            }
            else
            {
                insertTableDatas = new List<string[]>();
                foreach (DataGridViewRow item in this.dataGridView1.Rows)
                {
                    insertTableDatas.Add(new string[] {
                        item.Cells[1].FormattedValue.ToString(),
                        item.Cells[2].FormattedValue.ToString(),
                        //item.Cells[3].FormattedValue.ToString() ,
                        item.Cells[10].FormattedValue.ToString(),
                        item.Cells[5].FormattedValue.ToString(),
                        item.Cells[6].FormattedValue.ToString(),
                        item.Cells[7].FormattedValue.ToString(),
                        item.Cells[8].FormattedValue.ToString()
                    });
                }
                this.getBomFormData();
                this.Close(); //操作cad之前关闭窗口
                GValues.productCustCode = basProduct.custCode;
                GValues.productCode = basProduct.code;
                this.InsertTableSelection();
                basProduct.cadHandleId = GValues.cadHandleId;
                res = this.saveBomFormData(basProduct, gblProcessBoms, "拷贝");
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            //Http.CreateHttpClient(GValues.domainLink + "sys/common/upload?biz=" + "drawing/" + GValues.tenant, tenant, token).UploadFileAsync(@"C:\plot2pdf\aa.pdf", new Action<Http.HttpResp>((r1) =>
            //{
            //    var responCode = Convert.ToInt32(r1.Code);
            //    if (responCode == 200) //访问成功
            //    {

            //    }
            //    else
            //    {
            //        MessageBox.Show(r1.Code + " " + " " + responCode + " " + r1.Error);
            //    }
            //}));
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox17_TextChanged(object sender, EventArgs e)
        {

        }
        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1) //.OwningColumn.Name == "processId")
            {
                // 获取当前行
                DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex];
                String processId = currentRow.Cells[1].Value.ToString();

                foreach (BasProcess item in basProcessList)
                {
                    if (item.id == processId)
                    {
                        currentRow.Cells[10].Value = item.attribute;
                    }
                }
                this.dataGridView1.Invalidate();
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            this.dataGridView1.AllowDrop = true;
        }
     }
    #region winform input
    public class MultiSelectForm : Form
    {
        private CheckedListBox checkedListBox;
        private Button okButton;
        private Button cancelButton;
        private Action<List<ListItem>> callback;

        public List<ListItem> dataItems { get; private set; }

        public MultiSelectForm(List<ListItem> selectedItems, Action<List<ListItem>> callback)
        {
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Deactivate +=MultiSelectForm_Deactivate;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Height = 100;
            dataItems = new List<ListItem>();
            this.callback = callback;

            checkedListBox = new CheckedListBox
            {
                Dock = DockStyle.Fill
            };
            selectedItems.ForEach((item) =>
            {
                checkedListBox.Items.Add(item);
            });



            okButton = new Button
            {
                Text = "OK",
                DialogResult = DialogResult.OK
            };

            cancelButton = new Button
            {
                Text = "Cancel",
                DialogResult = DialogResult.Cancel
            };

            var buttonsPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Bottom,
                FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft,
                Padding = new Padding(5),
                Controls = { okButton, cancelButton }
            };

            Controls.AddRange(new Control[] { checkedListBox, buttonsPanel });
            okButton.Click += okButton_Click;
            okButton.Visible = false;
            cancelButton.Visible = false;
            cancelButton.Click += cancelButton_Click;
            checkedListBox.MouseClick += new MouseEventHandler(checkedListBox_MouseClick);
            checkedListBox.MouseDoubleClick += new MouseEventHandler(checkedListBox_MouseDoubleClick);

        }
        private void checkedListBox_MouseClick(object sender, MouseEventArgs e)
        {
            // 获取双击的索引
            int index = checkedListBox.IndexFromPoint(e.X, e.Y);//(MousePosition);

            if (index >= 0)
            {
                // 反选项
                checkedListBox.SetItemChecked(index, !checkedListBox.GetItemChecked(index));
            }
        }

        private void checkedListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 获取点击位置对应的行索引
            int index = checkedListBox.IndexFromPoint(e.X, e.Y);

            if (index >= 0)
            {
                // 行索引有效，可以执行你需要的操作
                // 例如：获取选中的项
                var item = checkedListBox.Items[index];
                
                if (callback != null)
                {
                    dataItems = new List<ListItem>();
                    dataItems.Add((ListItem)item);
                    callback.Invoke(dataItems);
                }
                //MessageBox.Show("双击的项: " + item.ToString());
            }
        }
        public void MultiSelectForm_Deactivate(object sender, Object e)
        {
            this.Close();
        }
        public void Form1_Load(object sender, Object e)
        {
            changgeLocation();
        }

        public void changgeLocation()
        {
            //获取父窗口坐标，FormZone是父窗口的类名
            int right = System.Windows.Forms.Application.OpenForms["BomForm"].Right;
            int top = System.Windows.Forms.Application.OpenForms["BomForm"].Top;
            this.Location = new Point(right, top);
        }

        public void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void okButton_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(checkedListBox.SelectedItems[0].ToString());
            if (checkedListBox.SelectedItems.Count > 0)
            {
                foreach (ListItem item in checkedListBox.CheckedItems)
                {
                    // 输出选定项的值
                    //Console.WriteLine("选定项的值: {" + item.Value + "}" + item.Text);
                    dataItems.Add(item);
                }
                if (callback != null)
                {
                    callback.Invoke(dataItems);
                }
            }
        }
    }
    #endregion
    public class ListItem
    {
        public string Text { get; set; }
        public string Value { get; set; }

        public ListItem(string text, string value)
        {
            Text = text;
            Value = value;
        }

        public override string ToString()
        {
            return Text;
        }
    }

    public class MrpProductBomVo
    {
        public String pid{get;set;}
        public String unitId{get;set;}
        public String productType{get;set;}
        public String status{get;set;}
        public String sizeLength { get; set; }
        public String sizeWidth { get; set; }
        public String productBomHandleId { get; set; }
        /**
         * 阶段(1量产2样品)
         */
        public String stage{get;set;}

        public List<MrpProductBom> mrpProductBoms{get;set;}
    }

    public class ProductBomTree
    {
    public String pid {get;set;}
    /**ID*/
    public String id {get;set;}
    /**类型2半成品3物料*/
    public String sizeLength { get; set; }
    public String sizeWidth { get; set; }
    public String handleId { get; set; }
    public String sort {get;set;}
    public String nodeType {get;set;}
    public String qty {get;set;}
    public String bomQty {get;set;}
    public String typeName {get;set;}
	/**产品编码*/
    public String unitId_dictText { get; set; }
    public String code {get; set;}
	/**客户料号*/

//	@Excel(name = "客户料号", width = 15)
    public String custCode {get;set;}
	/**图号*/

    public String drawingNo {get;set;}
	/**品名*/

    public String name {get;set;}

    public String realName { get; set; }
	/**描述*/

    public String description {get;set;}
	
	/**生产方式*/

	public String productionMethod {get;set;}
	
	public String remark {get;set;}
	public String version {get;set;}
	/**单位*/

    public String unitId {get;set;}

    public String hasChild {get;set;}

    public String assembleFlag {get;set;}
	
	public List<ProductBomTree> children {get;set;}
    public List<MrpProductBomMaterialProperty> materialProperties { get; set; }
    }
    public class MrpProductBom
    {
        public String handleId { get; set; }
        /**节点Id*/
    public String nodeId {get; set;}
    /**1产品2半成品*/
    public String nodeType {get; set;}
	/**父级节点*/
    public String pid {get; set;}
	/**单位*/

    public String unitId {get; set;}
	/**数量*/

    public String qty {get; set;}

	/**数量计算因子*/

    public String qtyFactor {get; set;}

	/**排序*/
    public String sort {get; set;}
    public String status {get; set;}
	/**是否有子节点*/


    public String hasChild {get; set;}
	/**备注*/

	public String remark {get; set;}
	/**损耗率*/

    public String lossRate {get; set;}

    public String assembleFlag {get; set;}

	public String materialQuality {get; set;}

	public String surface {get; set;}

	public String productionMethod {get; set;}
	/**创建人*/

    public String createBy {get; set;}
	/**创建日期*/

    public String createTime {get; set;}
	/**更新人*/

    public String updateBy {get; set;}
	/**更新日期*/


    public String updateTime {get; set;}
	/**businessId*/

    public String businessId {get; set;}
	/**tenantId*/

    public String tenantId {get; set;}

    }
    public class MrpProcessBom
    {
        public String id { get; set; }
        public int processSeq { get; set; }
        public String processId { get; set; }
        public String processId_dictText { get; set; }
        public List<ProcessRequirements> processRequirements { get; set; }
        public String processRequirements_dictText { get; set; }
        public String processRequirementDescs { get; set; }
        public String processAttribute { get; set; }
        public String processAttribute_dictText { get; set; }
        public String equipments { get; set; }
        public String leadTime { get; set; }
        public String processTime { get; set; }
        public String piecePrice { get; set; }
        public String remark { get; set; }
        public String productId { get; set; }
        public String processRequirement { get; set; }



    }
    //public class ResponResult<T>
    //{
    //    public Boolean success { get; set; }
    //    public string message { get; set; }
    //    public int code { get; set; }
    //    public T result { get; set; }
    //}

    public class ResponResultA<T>
    {
        public Boolean success { get; set; }
        public string message { get; set; }
        public int code { get; set; }
        public RetData<T> result { get; set; }
    }
    public class RetData<T>
    {
        public BindingList<T> records { get; set; }
        public int total { get; set; }
        public int size { get; set; }
        public int curren { get; set; }
        public int pages { get; set; }
    }

    public class BasProcess
    {
        public String id { get; set; }
        public String name { get; set; }
        public String processType { get; set; }

        public String attribute { get; set; }
        public List<BasProcessRequirement> processRequirements;
    }
    public class BasProcessRequirement
    {
        public String id { get; set; }
        public String name { get; set; }
        public String processId { get; set; }
    }

    public class ProcessAttribute
    {
       public ProcessAttribute(String _id, String _name)
        {
            id = _id;
            name = _name;
        }
        public String id { get; set; }
        public String name { get; set; }
    }
    public class ProcessRequirements
    {
        public String id { get; set; }
        public String name { get; set; }
    }
    public class LoginDTO
    {
        public UserInfo userInfo { get; set; }
        public List<Object> tenantList { get; set; }
        public string token { get; set; }
    }
    public class UserInfo
    {
        string username { get; set; }
        string realname { get; set; }

    }
    public class BasMaterial
    {
        	/**ID*/
    public String id {get; set;}
    /**物料类型*/
    public String unitId_dictText { get; set; }
    public String materialType {get; set;}
	public String typeName {get; set;}
	/**物料编码*/
    public String code {get; set;}
	/**客户料号*/
//	@Excel(name = "客户料号", width = 15)
    public String custCode {get; set;}
	/**品名*/
//	@Excel(name = "物料名称", width = 15,dictTable = "bas_material_category", dicText = "name", dicCode = "id")
    public String name {get; set;}
	public String nameDesc {get; set;}
	/**物料状态(正常(默认)/废止)*/
    public String sizeLength { get; set; }
    public String sizeWidth { get; set; }
    public String widthUnit { get; set; }
    public String widthUnit_dictText { get; set; }
    public String realName {get;set;}
    public String status {get; set;}
	/**规格*/
    public String model {get; set;}
	/**物料描述*/
    public String description {get; set;}
	/**图纸号*/
//	@Excel(name = "图纸号", width = 15)
    public String drawingNo {get; set;}
	/**图纸*/
//	@Excel(name = "图纸", width = 15)
    public String attachment {get; set;}
    public String area { get; set; }
	/**版本*/
    public String materialVer {get; set;}
	/**单位*/
    public String unitId {get; set;}
	public String unitName {get; set;}
	/**物料来源(外购(默认)/客供)*/
//	@Excel(name = "物料来源", width = 15,dicCode = "material_origin")
    public String source {get; set;}
	/**重量*/
//	@Excel(name = "重量", width = 15)
    public String weight {get; set;}
	/**最高限价*/
//	@Excel(name = "最高限价", width = 15)
	public String priceCeiling {get; set;}
	/**重量单位*/
//	@Excel(name = "重量单位", width = 15,dictTable = "bas_measure_unit", dicText = "name", dicCode = "id")
    public String weightUnit {get; set;}
	/**最小库存*/
//	@Excel(name = "最小库存", width = 15)
    public String minStock {get; set;}
	/**安全库存*/
//	@Excel(name = "安全库存", width = 15)
    public String safeStock {get; set;}
	/**最大库存*/
//	@Excel(name = "最大库存", width = 15)
    public String maxStock {get; set;}
    /*Excel 行号*/
	public String row {get; set;}
	/*Excel 列号*/
	public String col {get; set;}

	/*Excel 找到记录数*/
	public String findRecordTotal {get; set;}
	/**
	 * 数据查找反馈
	 */

	public String errMsg {get; set;}
	/**备注*/
    public String remark {get; set;}
	/**创建人*/
//	@Excel(name = "创建人", width = 15,dictTable = "sys_user",dicText = "realname",dicCode = "username")
    public String createBy {get; set;}
	/**创建时间*/
//	@Excel(name = "创建时间", width = 15, format = "yyyy-MM-dd HH:mm:ss")


    public String createTime {get; set;}
	/**修改人*/
//	@Excel(name = "修改人", width = 15,dictTable = "sys_user",dicText = "realname",dicCode = "username")

    public String updateBy {get; set;}
	/**修改时间*/
//	@Excel(name = "修改时间", width = 15, format = "yyyy-MM-dd HH:mm:ss")
    public String updateTime {get; set;}
	/**版本*/
//	@Excel(name = "版本", width = 15)
    public String version {get; set;}
	/**businessId*/
//	@Excel(name = "businessId", width = 15)
    public String businessId {get; set;}
	/**tenantId*/
//	@Excel(name = "tenantId", width = 15)
    public String tenantId {get; set;}
	/**
	 * 是否是复制物料
	 */
    public String isForCopy { get; set; }
	public String averagePrice {get; set;}


	public String averagePriceJson {get; set;}
	/**
	 * 被复制的物料ID
	 */
	public String oldMaterialId {get; set;}

    public String inventoryQty {get; set;}

	public List<BasMaterialProperty> basMaterialProperties {get; set;}
    }
    public class MrpProductBomMaterialProperty
    {
        /**ID*/

        public String id { get; set; }
        /**物料ID*/

        public String materialId { get; set; }
        /**编码*/

        public String code { get; set; }
        /**特征类型*/

        public String propertyType { get; set; }
        /**图形类型*/

        public String drawingType { get; set; }
        /**特征标签*/

        public String label { get; set; }
        /**半径*/

        public String redius { get; set; }
        /**颜色*/

        public String color { get; set; }
        /**名称*/

        public String name { get; set; }
        /**全名*/

        public String fullname { get; set; }
        /**是否启用*/

        public String isEnabled { get; set; }
        /**创建人*/
        public String createBy { get; set; }
        /**创建时间*/

        public String createTime { get; set; }
        /**修改人*/
        public String updateBy { get; set; }
        /**修改时间*/

        public String updateTime { get; set; }
        /**版本*/

        public String version { get; set; }
        /**businessId*/

        public String businessId { get; set; }
        public String handleId { get; set; }
        public String productId { get; set; }
        public String materialPropertyId { get; set; }
        /**tenantId*/

        public String tenantId { get; set; }
    }
    public class BasMaterialProperty {
        /**ID*/

    public String id {get; set;}
	/**物料ID*/

    public String materialId {get; set;}
	/**编码*/

    public String code {get; set;}
	/**特征类型*/

    public String propertyType {get; set;}
	/**图形类型*/

    public String drawingType {get; set;}
	/**特征标签*/

    public String label {get; set;}
	/**半径*/

    public String redius {get; set;}
	/**颜色*/

    public String color {get; set;}
	/**名称*/

    public String name {get; set;}
	/**全名*/

    public String fullname {get; set;}
	/**是否启用*/

    public String isEnabled {get; set;}
	/**创建人*/
    public String createBy {get; set;}
	/**创建时间*/

    public String createTime {get; set;}
	/**修改人*/
    public String updateBy {get; set;}
	/**修改时间*/

    public String updateTime {get; set;}
	/**版本*/

    public String version {get; set;}
	/**businessId*/

    public String businessId {get; set;}
    public String handleId { get; set; }
    public String productId { get; set; }
    public String materialPropertyId { get; set; }
	/**tenantId*/

    public String tenantId {get; set;}
    }
    public class BasProduct
    {

        public String id { get; set; }

        public String custId_dictText;
        public String productType_dictText { get; set; }
        public String code { get; set; }
        public String custCode { get; set; }

        public String customerDefCode { get; set; }
        public String drawingNo { get; set; }
        public String name { get; set; }
        public String productVer { get; set; }
        public String unitId_dictText { get; set; }
        public String unitId { get; set; }
        public String productionMethod { get; set; }

        public String productionMethod_dictText { get; set; }
        public String stage_dictText { get; set; }
        public String description { get; set; }
        public String remark { get; set; }
        public String weight { get; set; }
        public String weightUnit { get; set; }
        public String weightUnit_dictText { get; set; }
        public String sizeLength { get; set; }
        public String sizeWidth { get; set; }
        public String widthUnit { get; set; }
        public String widthUnit_dictText { get; set; }
        public String cadHandleId { get; set; }
        public String productBomHandleId { get; set; }
        public String attachment { get; set; }
        public bool createQrcodeInCad { get; set; }

        public String mainCompDesc { get; set; }
        //@Schema(name = "材料厚度")
        public String materialThickness { get; set; }
        //@Schema(name = "表面处理")
        public String faceProcess { get; set; }
        //@Schema(name = "体积单位")
        public String volumeUnit { get; set; }
        //@Schema(name = "体积")
        public String materialVolume { get; set; }
        //@Schema(name = "规格")
        public String model { get; set; }

        //@Dict(dictTable = "bas_supplier", dicText = "short_name", dicCode = "id")
        public String supplierId { get; set; }

        /**最高限价*/
        public String priceCeiling { get; set; }
        //@Dict(dicCode = "material_origin")
        public String source { get; set; }
        //@Dict(dictTable = "bas_material_category", dicText = "name", dicCode = "id")
        public String materialType { get; set; }

        //@Schema(description = "物料全称")
        public String fullName { get; set; }

    }
    public class ResponResult<T>
    {
        public Boolean success { get; set; }
        public string message { get; set; }
        public int code { get; set; }
        public T result { get; set; }
    }
    public static class BindingListExtensions
    {
        public static void Sort<T>(this BindingList<T> bindingList, Func<T, object> sortBy)
        {
            var sortedList = bindingList.OrderBy(sortBy).ToList();
            bindingList.Clear();
            foreach (var item in sortedList)
            {
                bindingList.Add(item);
            }
        }
    }

   public class BasProductImport {

    public String id{ get; set; }
    public String importQty { set; get; }
    public String cadHandleId { get; set; }
    public String productTypeName{ get; set; }
	public String productType{ get; set; }
	public String productOriginName{ get; set; }
	public String productOrigin{ get; set; }
    public String sizeLength { get; set; }
    public String sizeWidth { get; set; }
    public String widthUnit { get; set; }
    public String widthUnit_dictText { get; set; }
	public String productionMethodName{ get; set; }
	public String productionMethod{ get; set; }
	
    public String code{ get; set; }
    public String mainCode { get; set; }

	public String customerCode{ get; set; }

	public String customerName{ get; set; }
	/**客户料号*/

    public String custCode{ get; set; }
	/**图号*/

    public String drawingNo{ get; set; }
	/**品名*/

    public String mainName { get; set; } 
    public String name{ get; set; }
	/**状态(1正常2废止)*/

    public String statusName{ get; set; }
	public String status{ get; set; }
	/**描述*/

    public String description{ get; set; }

	public String remark{ get; set; }
	/**图纸*/

    public String attachment{ get; set; }


	public String localAttachment{ get; set; }

	/**版本*/

    public String productVer{ get; set; }
	/**单位*/

    public String unitName{ get; set; }
	public String unitId{ get; set; }
	/**阶段(1量产2样品)*/

    public String stageName{ get; set; }
	public String stage { get; set; }
	
	/**单价*/

    public String unitPrice{ get; set; }
	/**币种*/

    public String currencyName{ get; set; }
	public String currency{ get; set; }
	/**重量*/

    public String weight{ get; set; }

	public String excelRow{ get; set; }
	/**
	 * 错诶信息
	 */
	public String errorMsg{ get; set; }
	/**
	 * 错误数据
	 */
	public Boolean errorData { get; set; }
	/**
	 * 警告数据(可以再次批量添加)
	 */
	public Boolean warnData { get; set; }

       //	@Schema(name = "材料")
    public String mainCompDesc { get; set; }
	//@Schema(name = "材料厚度")
    public String materialThickness { get; set; }
	//@Schema(name = "表面处理")
    public String faceProcess { get; set; }
	//@Schema(name = "体积单位")
    public String volumeUnit { get; set; }
	//@Schema(name = "体积")
    public String materialVolume { get; set; }
	//@Schema(name = "规格")
    public String model { get; set; }

	//@Dict(dictTable = "bas_supplier", dicText = "short_name", dicCode = "id")
    public String supplierId { get; set; }

	/**最高限价*/
    public String priceCeiling { get; set; }
	//@Dict(dicCode = "material_origin")
    public String source { get; set; }
	//@Dict(dictTable = "bas_material_category", dicText = "name", dicCode = "id")
    public String materialType { get; set; }

	//@Schema(description = "物料全称")
    public String fullName { get; set; }

}
}
